Pipelining

共享一条connection,以减少因为网络连接导致的性能问题:

List<Object> results = stringRedisTemplate.executePipelined(
  new RedisCallback<Object>() {
    public Object doInRedis(RedisConnection connection) throws DataAccessException {
      StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
      for(int i=0; i< batchSize; i++) {
        stringRedisConn.rPop("myqueue");
      }
    return null;
  }
});

transaction

redis中的事务

List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() {
  public List<Object> execute(RedisOperations operations) throws DataAccessException {
    operations.multi();
    operations.opsForSet().add("key", "value1");

    // This will contain the results of all ops in the transaction
    return operations.exec();
  }
});
System.out.println("Number of items added to set: " + txResults.get(0));

demo

    @Test
    public void genrete() {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        for (int i = 0; i < 2000; i++) {
            valueOperations.set("hello" + i, String.valueOf(i));
        }
        System.out.println("gen ok");
    }

    @Test
    public void forGet() {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 2000; i++) {
            String hello = valueOperations.get("hello" + i);
            System.out.println(hello);
        }
        System.out.println("cost for get " + (System.currentTimeMillis() - start));
        // cost for get 2458 ms
    }

    @Test
    public void forPipline() {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        long start = System.currentTimeMillis();

        List<Object> list = redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                redisConnection.openPipeline();
                for (int i = 0; i < 2000; i++) {
                    redisConnection.get(("hello" + i).getBytes());
                }
                return null;//注意,这里一定要返回null
            }
        }, redisTemplate.getKeySerializer());

        for (Object hello : list) {
            System.out.println(hello);
        }
        System.out.println("cost for piple " + (System.currentTimeMillis() - start));
        // cost for piple 121 ms
    }

使用问题

ERR Protocol error: invalid multibulk length

一下子执行的redis的命令大小太大,比如下面的:

        final String keysPattern = CcRedisKeyUtils.Session.getCleanSessionObjectKeys(userId);
        //Set<String> ks = hashOps.getOperations().keys(keysPattern);
        final Set<String> ks = RedisKeysPatternUtils.getKeys(hashOps.getOperations(), keysPattern);
        hashOps.getOperations().delete(ks);

参考资料

参考资料

  1. Spring-data-redis