首页 > 解决方案 > 如何在 Java 中使用 Redis 命令“bitcount”

问题描述

我正在尝试使用redis位图保存在线用户,使用命令“bitcount onlineUser”来统计在线用户数。我使用RedisTemplate来处理redis。但我在 RedisTemplate 中找不到任何 API 来执行命令“bitcount”。如何在 java 中执行命令“bitcount”?任何帮助将不胜感激。

 @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().;
    }

标签: javaspringspring-bootredis

解决方案


您可以使用 RedisTemplate 的“执行”方法,例如:

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);
        }
    });
}

推荐阅读