一、流水线:
redis的读写速度十分快,所以系统的瓶颈往往是在网络通信中的延迟。
redis可能会在很多时候处于空闲状态而等待命令的到达。
为了解决这个问题,可以使用redis的流水线,流水线是一种通讯协议,类似一个队列批量执行一组命令。
二、流水线使用/对比:
1、未使用流水线处理10000次请求:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:redis.xml") public class RedisTest { @Autowired private RedisTemplate redisTemplate; @Test public void test(){ // 开始时间 long start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { redisTemplate.opsForValue().set("k"+i,"v"+i); } // 结束时间 long end = System.currentTimeMillis(); System.out.println(end-start); } }
//耗时:5692;
2、使用流水线:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:redis.xml") public class RedisTest { @Autowired private RedisTemplate redisTemplate; @Test public void test(){ // 开始时间 long start = System.currentTimeMillis(); redisTemplate.executePipelined(new SessionCallback() { //执行流水线 public Object execute(RedisOperations operations) throws DataAccessException { //批量处理的内容 for (int i = 0; i < 20000; i++) { operations.opsForValue().set("k"+i,"v"+i); } return null; } }); // 结束时间 long end = System.currentTimeMillis(); System.out.println(end-start); } }
//耗时:309;