spring redis 使用笔记
PS: 要按照实际业务场景以及实际瓶颈去优化工具的使用,而不是盲从优化建议。
SCAN
在 redis 中如果 key 的数量非常多的话,使用 KEYS
命令可能非常慢,可以使用游标的方式增量是获取 key。
protected Set<String> keySet2(String pattern) {
List<byte[]> rawBinaryKeys =
redisTemplate.execute(new RedisCallback<List<byte[]>>() {
@Override
public List<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
Object nativeConnection = connection.getNativeConnection();
List<byte[]> binaryKeys = Lists.newArrayList();
Cursor<byte[]> cursor = connection.scan(ScanOptions.
scanOptions()
.count(10000)
.match(pattern)
.build());
while (cursor.hasNext()) {
byte[] key = cursor.next();
binaryKeys.add(key);
}
// try {
// cursor.close(); // The new version don not close here
// } catch (Exception e) {
// }
return binaryKeys;
}
});
List keyList = SerializationUtils.deserialize(rawBinaryKeys, redisTemplate.getKeySerializer());
return Sets.newHashSet(keyList);
}