public void testRedisPipeline() {
// 先往redis中放置6个key
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6);
for (int i = 0; i < list.size(); i++) {
Integer element = list.get(i);
redisTemplate.executePipelined((RedisCallback<String>) redisConnection -> {
String redisKey = "testRedisPipeline_" + element;
redisConnection.hSet(redisKey.getBytes(), String.valueOf(1).getBytes(), (element + "_test").getBytes());
// 模拟一个key失效
if (element == 3) {
redisConnection.hDel(redisKey.getBytes(), String.valueOf(1).getBytes());
}
return null;
});
}
// 批量获取key
List<String> returnList = redisTemplate.executePipelined((RedisCallback<String>) redisConnection -> {
for (Integer userId : list) {
String redisKey = "testRedisPipeline_" + userId;
redisConnection.hGet(redisKey.getBytes(), String.valueOf(1).getBytes());
}
return null;
}, redisTemplate.getStringSerializer());
System.out.println("source list detail: " + list.toString());
System.out.println("return list size: " + returnList.size());
System.out.println("return list detail: " + returnList.toString());
for (String userId : returnList) {
if (StringUtils.isNotBlank(userId)) {
System.out.println(userId);
}
}
}
输出:
[1,2,3,4,5,6]
6
[1,2,null,4,5,6]
1_test
2_test
4_test
5_test
6_test
评论