我正在尝试使用redis位图来保存在线用户,使用"bitcount onlineUser“命令来统计在线用户的数量。我使用RedisTemplate来处理redis。但是我在RedisTemplate中找不到任何接口来执行"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().;
}发布于 2020-09-02 09:50:10
您可以使用RedisTemplate的execute方法,例如:
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);
}
});
}发布于 2021-11-24 05:17:13
如果你使用的是spring,你可以像下面这样使用bitCount操作。
redisTemplate.execute { connection ->
connection.stringCommands().bitCount(key.toByteArray())
}https://stackoverflow.com/questions/60409641
复制相似问题