redis muti get笔记

RedisTemplate:通过RedisTemplate获取字节数组(byte[])

原文:https://www.codeleading.com/article/27755177535/

 

public byte[] get(byte[] key) {
    // 使用了lambda表达式
    return redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.get(key));
}

 

public byte[] get(byte[] key) {
    return redisTemplate.execute(new RedisCallback<byte[]>() {
        @Override
        public byte[] doInRedis(RedisConnection redisConnection) throws DataAccessException {
            // 传入byte[]类型的key,获取byte[]类型的value
            byte[] bytes = redisConnection.get(key);
            return bytes;
        }
    });
}

 

muti-get

    @Autowired
    private StringRedisTemplate redisTemplate;
  
    public List<String> mget(List<String> keys) {
        return redisTemplate.opsForValue().multiGet(keys);
    }

 

connection /callback的 muti-get

List<byte[]> bytesList = redisTemplate.execute((RedisConnection conn) -> conn.mGet(realKeys.toArray(rawKeys)));

 

还有一个pipeline方式,可以单独处理没有命中时的结果,速度介于mget 和  batch-loop-get。

原文:Redis 批量查询优化 https://www.jianshu.com/p/a2e9f03cd34c

   /**
     * 批量查询 pipeline
     * @param keys
     * @return
     */
    @GetMapping("/batchGet")
    public List<Object> batchGet(String... keys){
        List<String> keysList = Arrays.asList(keys);
        return redisOperator.batchGet(keysList);
    }
@Component
public class RedisOperator {


    @Autowired
    private StringRedisTemplate redisTemplate;
  
     /**
     * 批量查询 管道 pipeline
     *
     * @param keys
     * @return value
     */
    public List<Object> batchGet(List<String> keys) {
        // nginx -> keepalive
        // redis -> pipeline
        List<Object> result = redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                StringRedisConnection src = (StringRedisConnection) connection;
                for (String key : keys) {
                    src.get(key);
                }
                return null;
            }
        });
        return result;
    }
  
}

 

 

Redis 批量查询优化

posted @ 2021-11-08 10:44  multitude  阅读(1016)  评论(0编辑  收藏  举报