Redis管道

Redis之管道的使用java

原文地址: https://blog.piaoruiqing.com/blog/2019/06/24/redis管道redis

关键词

Redis Pipelining: 客户端能够向服务器发送多个请求而无需等待回复, 最后只需一步便可读取回复.数据库

RTT(Round Trip Time): 往返时间.bash

为何要用管道

Redis是使用client-server模型和Request/Response协议的TCP服务器. 这意味着一般经过如下步骤完成请求:服务器

  • 客户端向服务器发送查询, 并一般以阻塞方式从套接字读取服务器响应.
  • 服务器处理该命令并将响应发送回客户端.

应用程序与Redis经过网络进行链接, 可能很是快(本地回环), 也可能很慢. 但不管网络延迟是多少, 数据包都须要时间从客户端传输到服务器, 而后从服务器返回到客户端以进行回复(此时间称为RTT). 当客户端须要连续执行许多请求时(例如, 将多个元素添加到同一列表或使用多个键填充数据库), 很容易发现这种频繁操做很影响性能. 使用管道将屡次操做经过一次IO发送给Redis服务器, 而后一次性获取每一条指令的结果, 以减小网络上的开销.网络

频繁操做但未使用管道的情形以下图:async

使用管道后以下图: 分布式

如何使用

Jedis

/** jedis pool */
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
private static final JedisPool POOL =
    new JedisPool(new JedisPoolConfig(), "test-redis-server", 6379);
/** * test pipelining with Jedis */
@Test
public void testPipelining() {

    try (Jedis jedis = POOL.getResource()) {

        Pipeline pipelined = jedis.pipelined();	// (一)
        Response<String> response1 = pipelined.set("mykey1", "myvalue1");
        Response<String> response2 = pipelined.set("mykey2", "myvalue2");
        Response<String> response3 = pipelined.set("mykey3", "myvalue3");

        pipelined.sync();	// (二)

        LOGGER.info("cmd: SET mykey1 myvalue1, result: {}", response1.get());	// (三)
        LOGGER.info("cmd: SET mykey2 myvalue2, result: {}", response2.get());
        LOGGER.info("cmd: SET mykey3 myvalue3, result: {}", response3.get());
    }
}
复制代码
  • (一): jedis.pipelined(): 获取一个Pipeline用以批量执行指令.
  • (二): pipelined.sync(): 同步执行, 经过读取所有Response来同步管道, 这个操做会关闭管道.
  • (三): response1.get(): 获取执行结果. 注意: 在执行pipelined.sync()以前, get是没法获取到结果的.

Lettuce

private final Logger LOGGER = LoggerFactory.getLogger(getClass());

/** redis client */
private static final RedisClient CLIENT
        = RedisClient.create("redis://@test-redis-server:6379/0");
/** * test pipelining with Lettuce */
@Test
public void testPipelining() throws ExecutionException, InterruptedException {

    try (StatefulRedisConnection<String, String> connection = CLIENT.connect()) {

        RedisAsyncCommands<String, String> async = connection.async();
        async.setAutoFlushCommands(false);
        RedisFuture<String> future1 = async.set("mykey1", "myvalue1");
        RedisFuture<String> future2 = async.set("mykey2", "myvalue2");
        RedisFuture<String> future3 = async.set("mykey3", "myvalue3");

        async.flushCommands();

        LOGGER.info("cmd: SET mykey1 myvalue1, result: {}", future1.get());
        LOGGER.info("cmd: SET mykey2 myvalue2, result: {}", future1.get());
        LOGGER.info("cmd: SET mykey3 myvalue3, result: {}", future1.get());
    }
}
复制代码

RedisTemplate

private final Logger LOGGER = LoggerFactory.getLogger(getClass());

@Resource
private StringRedisTemplate stringRedisTemplate;

/** * test pipelining with RedisTemplate */
@Test
public void testPipelining() {

    List<Object> objects 
        = stringRedisTemplate.executePipelined((RedisCallback<Object>)connection -> {

        connection.set("mykey1".getBytes(), "myvalue1".getBytes());
        connection.set("mykey2".getBytes(), "myvalue2".getBytes());
        connection.set("mykey3".getBytes(), "myvalue3".getBytes());
        return null;	// (一)
    });

    LOGGER.info("cmd: SET mykey myvalue, result: {}", objects);
}
复制代码
  • (一): 此处必须返回null

简单对比测试

redis服务器运行在同一个路由器下的树莓派上.post

/** * pipeline vs direct */
@Test
public void compared() {

    try (Jedis jedis = POOL.getResource()) {   // warm up
        jedis.set("mykey", "myvalue");
    }

    try (Jedis jedis = POOL.getResource()) {
        long start = System.nanoTime();
        Pipeline pipelined = jedis.pipelined();
        for (int index = 0; index < 500; index++) {
            pipelined.set("mykey" + index, "myvalue" + index);
        }
        pipelined.sync();
        long end = System.nanoTime();
        LOGGER.info("pipeline cost: {} ns", end - start);
    }

    try (Jedis jedis = POOL.getResource()) {
        long start = System.nanoTime();
        for (int index = 0; index < 500; index++) {
            jedis.set("mykey" + index, "myvalue" + index);
        }
        long end = System.nanoTime();
        LOGGER.info("direct cost: {} ns", end - start);
    }
}
复制代码

使用Jedis执行500条set, 执行结果以下:性能

22:16:00.523 [main] INFO - pipeline cost:   73681257 ns		// 管道
22:16:03.040 [main] INFO - direct cost  : 2511915103 ns		// 直接执行
复制代码

500次set执行时间总和已经和管道执行一次的所消耗的时间不在一个量级上了.

扩展

摘自redis官方文档

使用管道不单单是为了下降RTT以减小延迟成本, 实际上使用管道也能大大提升Redis服务器中每秒可执行的总操做量. 这是由于, 在不使用管道的状况下, 尽管操做单个命令开起来十分简单, 但实际上这种频繁的I/O操做形成的消耗是巨大的, 这涉及到系统读写的调用, 这意味着从用户域到内核域.上下文切换会对速度产生极大的损耗.

使用管道操做时, 一般使用单个read() 系统调用读取许多命令,并经过单个write()系统调用传递多个回复. 所以, 每秒执行的总查询数最初会随着较长的管道线性增长, 并最终达到不使用管道技术获的10倍, 以下图所示:

系列文章

  1. Redis入门
  2. Redis使用进阶
  3. Redis分布式锁

参考文献

[版权声明]
本文发布于 朴瑞卿的博客, 容许非商业用途转载, 但转载必须保留原做者 朴瑞卿 及连接: blog.piaoruiqing.com. 若有受权方面的协商或合做, 请联系邮箱: piaoruiqing@gmail.com.
相关文章
相关标签/搜索