美文网首页
redis pipeline简介

redis pipeline简介

作者: OneFish | 来源:发表于2016-08-26 11:42 被阅读4501次

    java中redis的pipeline

    pipeline方式执行redis操作:

    List<Object> results = this.getRedisTemplate().executePipelined(new RedisCallback<Object>() {
        @Override
        public Object doInRedis(RedisConnection connection) throws DataAccessException {
            RedisSerializer<String> keySerializer=new StringRedisSerializer();
            for (String key : keys) {
                connection.get(keySerializer.serialize(key));
            }
            return null;
        }
    });
    

    doInRedis方法中实现需要的redis操作

    RedisTemplate中的executePipelined方法:

    public List<Object> executePipelined(final RedisCallback<?> action) {
        return executePipelined(action, valueSerializer);
    }
    
    public List<Object> executePipelined(final RedisCallback<?> action, final RedisSerializer<?> resultSerializer) {
        return execute(new RedisCallback<List<Object>>() {
            public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
                connection.openPipeline();
                boolean pipelinedClosed = false;
                try {
                    Object result = action.doInRedis(connection);
                    if (result != null) {
                        throw new InvalidDataAccessApiUsageException(
                                "Callback cannot return a non-null value as it gets overwritten by the pipeline");
                    }
                    List<Object> closePipeline = connection.closePipeline();
                    pipelinedClosed = true;
                    return deserializeMixedResults(closePipeline, resultSerializer, resultSerializer, resultSerializer);
                } finally {
                    if (!pipelinedClosed) {
                        connection.closePipeline();
                    }
                }
            }
        });
    }
    
    注意
    • doInRedis中的redis操作不会立刻执行
    • 所有redis操作会在connection.closePipeline()之后一并提交到redis并执行,这是pipeline方式的优势
    • 所有操作的执行结果为executePipelined()的返回值

    相关文章

      网友评论

          本文标题:redis pipeline简介

          本文链接:https://www.haomeiwen.com/subject/iqfzsttx.html