您的位置:首页 > 数据库 > Redis

RedisTemplate SCAN 命令的使用和注意事项

2017-03-20 00:00 1596 查看
spring-data-redis
提供了
RedisTemplate
类以简化和统一对 Redis 的访问。

使用 HSCAN 命令类似于:

String key = "key";
BoundHashOperations<String, String, Long> boundHashOps = redisTemplate.boundHashOps(key);
try (Cursor<Map.Entry<String, Long>> cursor = boundHashOps.scan(
ScanOptions.scanOptions().count(1000).build())) {
while (cursor.hasNext()) {
Map.Entry<String, Long> entry = cursor.next();
// do sth.
} catch (IOException e) {
}

注意,Cursor 是需要在用完后是需要手动关闭连接的,我们可以使用 try catch 的语法来自动执行
Closable
接口的
close()
方法,如上例。

默认没有提供 SCAN 命令,我们可以手动实现:

public class RedisHelper {

@SuppressWarnings("unchecked")
public static Cursor<String> scan(RedisTemplate redisTemplate, String pattern, int limit) {
ScanOptions options = ScanOptions.scanOptions().match(pattern).count(limit).build();
RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
return (Cursor) redisTemplate.executeWithStickyConnection(new RedisCallback() {
@Override
public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
return new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize);
}
});
}
}

注意这里使用了
executeWithStickyConnection
,因为 SCAN 需要在同一条连接上执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java Redis