skip to Main Content

On Spring Boot

I want to get millis of Redis server with RedisTemplate.

Like this

redis> TIME

  1. "1687736427"
  2. "339025"
    redis> TIME
  3. "1687736427"
  4. "339285"
    redis>

But reference says, "Template does not Support Time".

Is there no way?

/* thank you!! lant. My code look like */
this.redisTemplate.execute(new SessionCallback<Long>() {
    @Override
    public Long execute(RedisOperations operations) throws DataAccessException {            
        do {
            Long now = redisTemplate.execute(new RedisCallback<Long>() {
                @Override
                public Long doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.time();
                }
            });
        } while() 
    }
}

2

Answers


  1. RedisTemplate provides an execute method that can execute Redis Command.

      Object execute = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
                return redisConnection.time();
            }
        });
    

    Actually, other redisTemplate methods like get() also execute using execute(RedisCallback<T> callback).

    redisTemplate.opsForValue().get("key");
    

    get source code is

    @Override
    public V get(Object key) {
    
        return execute(new ValueDeserializingRedisCallback(key) {
    
            @Override
            protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
                return connection.get(rawKey);
            }
        });
    }
    
    
    @Nullable
    <T> T execute(RedisCallback<T> callback) {
        return template.execute(callback, true);
    }
    
    Login or Signup to reply.
  2. You can use the execute method of RedisTemplate to execute the Redis command to obtain the server time. The specific implementation is as follows:

    @Autowired
    private RedisTemplate redisTemplate;
    
    public String getServerTime() {
           return (String) redisTemplate.execute((RedisCallback<String>) connection 
         -> connection.time().toString());
    }
    

    RedisCallback is used to encapsulate the Redis command. Here, the time command is used to obtain the server time. The return value is an array. The first element is the Unix time timestamp of the current time, and the second element is the microseconds. Use the toString method to convert an array into a string and return it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search