写点什么

Redis Pipeline

作者:new life
  • 2021 年 11 月 09 日
  • 本文字数:1017 字

    阅读完需:约 3 分钟

Redis Pipeline

Redis Pipelining

A Request/Response server can be implemented so that it is able to process new requests even if the client hasn't already read the old responses. This way it is possible to send multiple commands to the server without waiting for the replies at all, and finally read the replies in a single step.


redis pipeline 是为了减少网络交互次数,一次将多个命令发送到 redis server 端,等到多个命令全部执行完后再返回结果;


传统的请求:

A 请求 -> A 响应

B 请求 -> B 响应

C 请求 -> C 响应


Pipeline

A 请求

B 请求

C 请求

......


A 响应

B 响应

C 响应

......


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_test2_test4_test5_test6_test


复制代码


用户头像

new life

关注

还未添加个人签名 2019.03.04 加入

还未添加个人简介

评论

发布
暂无评论
Redis Pipeline