pipeline是redis批量提交的一种方式,也就是把多个命令操作建立一次连接发给redis去执行,在性能方面会比循环的单次提交会好很多。
public void testOne() { long begin = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { redisTemplate.boundValueOps(i + "a").set(i); } long end = System.currentTimeMillis(); System.out.println("每次都连接耗时:" + (end - begin) + "毫秒"); }每次都连接耗时:2954毫秒
public void testPipeline() { long begin = System.currentTimeMillis(); redisTemplate.executePipelined(new RedisCallback<Long>() { public Long doInRedis(RedisConnection connection) throws DataAccessException { connection.openPipeline(); for (int i = 0; i < 10000; i++) { byte[] key = ("pipeline" + i ).getBytes(); byte[] value = ("pipeline" + i ).getBytes(); connection.set(key, value); } //connection.closePipeline(); return null; } }); long end = System.currentTimeMillis(); System.out.println("一次连接耗时:" + (end - begin) + "毫秒"); }一次连接耗时:87毫秒
可见性能提升是很显著的。
另外直接使用jedis的pipeline,你会发现速度更快少量。
注意在使用pipeline以后,在回调方法中我们需要使用原生的redis接口,而其中大部分都是字节型的参数,需要我们进行转换获取字节流,而后进行存储或者读取。
通过pipeline方式存取的key,在使用redisTemplate读取时会遇到Null的问题,这是因为key值序列化的方法不一样造成的,为了避免这种情况,我们可以对redisTemplate进行设置,代码如下
redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new StringRedisSerializer());以后即可以通过redisTemplate.boundValueOps("pipeline0").get()
轻松读取pipeline存储的内容了。