五.redis pipeline
redis是一个cs模式的tcp server,使用和http类似的请求响应协议。一个client可以通过一个socket连接发起多个请求命令。每个请求命令发出后client通常 会阻塞并等待redis服务处理,redis处理完后请求命令后会将结果通过响应报文返回给client。基本的通信过程如下
Client: INCR XServer: 1Client: INCR XServer: 2Client: INCR XServer: 3Client: INCR XServer: 4基 本上四个命令需要8个tcp报文才能完成。由于通信会有网络延迟,假如从client和server之间的包传输时间需要0.125秒。那么上面的四个命 令8个报文至少会需要1秒才能完成。这样即使redis每秒能处理100个命令,而我们的client也只能一秒钟发出四个命令。这显示没有充分利用 redis的处理能力。除了可以利用mget,mset 之类的单条命令处理多个key的命令外
Client: INCR XClient: INCR XClient: INCR XClient: INCR XServer: 1Server: 2Server: 3Server: 4假 设不会因为tcp 报文过长而被拆分。可能两个tcp报文就能完成四条命令,client可以将四个incr命令放到一个tcp报文一起发送,server则可以将四条命令 的处理结果放到一个tcp报文返回。通过pipeline方式当有大批量的操作时候。我们可以节省很多原来浪费在网络延迟的时间。需要注意到是用 pipeline方式打包命令发送,redis必须在处理完所有命令前先缓存起所有命令的处理结果。打包的命令越多,缓存消耗内存也越多。所以并是不是打 包的命令越多越好。具体多少合适需要根据具体情况测试。下面是个jredis客户端使用pipeline的测试
package jredisStudy;import org.jredis.JRedis;import org.jredis.connector.ConnectionSpec;import org.jredis.ri.alphazero.JRedisClient;import org.jredis.ri.alphazero.JRedisPipelineService;import org.jredis.ri.alphazero.connection.DefaultConnectionSpec;public class PipeLineTest { public static void main(String[] args) { long start = System.currentTimeMillis(); usePipeline(); long end = System.currentTimeMillis(); System.out.println(end-start); start = System.currentTimeMillis(); withoutPipeline(); end = System.currentTimeMillis(); System.out.println(end-start); } private static void withoutPipeline() { try { JRedis jredis = new JRedisClient("192.168.56.55",6379); for(int i =0 ; i < 100000 ; i++) { jredis.incr("test2"); } jredis.quit(); } catch (Exception e) { } } private static void usePipeline() { try { ConnectionSpec spec = DefaultConnectionSpec.newSpec("192.168.56.55", 6379, 0, null); JRedis jredis = new JRedisPipelineService(spec); for(int i =0 ; i < 100000 ; i++) { jredis.incr("test2"); } jredis.quit(); } catch (Exception e) { } }}输出