Spring中执行流水线,使用RedisTemplate提供的executePipelined方法即可.
@Test
public void xx() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
final RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
SessionCallback sessionCallback = (SessionCallback)(RedisOperations ops) ->{
for(int i=0;i<10000;i++){
int j=i+1;
ops.boundValueOps("pipeline_key"+j).set("pipeline_value"+j);
ops.boundValueOps("pipeline_key"+j).get();
}
return null;
};
long start = System.currentTimeMillis();
List resultList = redisTemplate.executePipelined(sessionCallback);
long end = System.currentTimeMillis();
System.out.println(end-start);
System.out.println(resultList);
}
输出:
**461**
[true, pipeline_value1, true, pipeline_value2, true, pipeline_value3, 等等
注意:
流水线会返回一个List,保存执行多个命令结果,但是当命令很多的时候就得考虑使用迭代的方法去处理,不然内存不足发生JVM会发生溢出错误。
为了测试流水线的效率:我写了同样的代码,但是没有使用流水线:
@Test
public void xx() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
final RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
long start = System.currentTimeMillis();
for(int i=0;i<10000;i++){
int j=i+1;
redisTemplate.opsForValue().set("key"+j,"value"+j);
redisTemplate.opsForValue().get("key"+j);
}
long end = System.currentTimeMillis();
System.out.print(end-start);
}
输出:
1316
效率比使用流水线慢了不只两倍。
提一嘴:
在使用流水线的时候,要考虑其对运行环境内存空间的开销,主要是list的存储,可以考虑迭代.