skip to Main Content

I am trying to use redis bitmap to save online user, use command “bitcount onlineUser” to count the number of online user.I use RedisTemplate to deal with redis. But I can’t find any API in RedisTemplate to execute command “bitcount’.How can I execute command “bitcount” in java? Any help will be appreciated.

 @Override
    public Boolean saveOnlineUser(Long userId) {
        ValueOperations<String,Object> ops = redisTemplate.opsForValue();
        return ops.setBit("onlineUser",userId,true);
    }

    @Override
    public Integer getOnlineUser() {
        //I want to use Redis command "bitcount 'onlineUser'" here to count the number of online users
        return redisTemplate.opsForValue().;
    }

2

Answers


  1. You can use the "execute" method of RedisTemplate, for example:

    public Long bitcount(final String key, final long start, final long end) {
        return redisTemplate.execute(new RedisCallback<Long>() {
    
            @Override
            public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
    
                return redisConnection.bitCount(key.getBytes(), start, end);
            }
        });
    }
    
    Login or Signup to reply.
  2. if you use spring, you can use bitCount operation like below.

    redisTemplate.execute { connection ->
            connection.stringCommands().bitCount(key.toByteArray())
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search