You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中RedisTemplate不支持TIME命令,如何获取Redis服务器时间?

在Spring Boot中通过RedisTemplate获取Redis服务器时间戳(毫秒级)

核心实现思路

RedisTemplate确实没有直接封装TIME命令,但可以通过直接操作RedisConnection来实现——RedisConnection接口提供了time()方法,能直接调用Redis的TIME命令。

明确Redis TIME命令的返回逻辑

Redis的TIME命令返回两个整数值:

  1. 第一个是自Unix纪元以来的秒数
  2. 第二个是当前秒内的微秒数

要得到毫秒级时间戳,需通过公式计算:秒数 * 1000 + 微秒数 / 1000

正确代码示例

1. 单次获取Redis服务器时间(最简写法)

// 获取Redis服务器的毫秒级时间戳
Long redisServerTimeMs = redisTemplate.execute((RedisCallback<Long>) connection -> {
    long[] time = connection.time();
    // 转成毫秒级时间戳
    return time[0] * 1000 + time[1] / 1000;
});

2. 结合SessionCallback的循环场景(适配你代码里的do-while需求)

如果需要在同一个连接会话中循环执行操作,用SessionCallback保持连接上下文:

Long finalRedisTimeMs = redisTemplate.execute((SessionCallback<Long>) operations -> {
    Long targetTime = null;
    do {
        long[] time = operations.execute((RedisCallback<long[]>) connection -> connection.time());
        targetTime = time[0] * 1000 + time[1] / 1000;
        // 补充你的循环终止条件,比如判断时间是否达到预期阈值
    } while (/* 你的循环条件,例如:targetTime < System.currentTimeMillis() + 5000 */);
    return targetTime;
});

修正你代码中的问题

你之前的代码存在编译错误:connection.time()返回的是long[]类型,不是Long,不能直接返回。必须先接收这个数组,再计算成毫秒级时间戳。

内容的提问来源于stack exchange,提问作者jin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:40:04