Redis的Pipeline管道操作,节约网络开销

181 阅读1分钟

Redis 管道技术可以在服务端未响应时,客户端可以继续向服务端发送请求,并最终一次性读取所有服务端的响应。

Pipeline 实现的原理是队列,而队列的原理是时先进先出,这样就保证数据的顺序性

代码如下:

1,jedis jar 包引入

 
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

2,代码实现

package com.hcmony.sword.redis;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Transaction;

/**
 * <h3>redis 管道处理</h3>
 * <p></p>
 *
 * @author hcmony
 * @since V1.0.0, 2019/05/06 20:07
 */
public abstract class RedisCahePipelineHelper {

	private final JedisPool jedisPool;

	public RedisCahePipelineHelper(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	public Object pipeline(){
		Jedis jedis = null;
		Pipeline pipeline = null;
		try {
			jedis = jedisPool.getResource();
			pipeline = jedis.pipelined();
			return doSerive(pipeline);
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
		finally {
			if (null != jedis) {
				jedis.close();
			}
		}
	}

	protected abstract Object doSerive(Pipeline pipeline);


	static class Test extends RedisCahePipelineHelper {

		public Test(JedisPool jedisPool) {
			super(jedisPool);
		}

		@Override
		protected Object doSerive(Pipeline pipeline) {
			pipeline.hset("a","1","3");
			pipeline.hset("a","2","4");
			pipeline.sync();
			pipeline.hget("a","1");
			pipeline.hget("a","2");
			return pipeline.syncAndReturnAll();
		}


		public static void main(String[] args) {
			//默认连接本地redis,
			// loclhost:6379
			JedisPool jedisPool = new JedisPool();
			Test test = new Test(jedisPool);
			Object o = test.pipeline();
			System.out.println(JSONObject.toJSONString(o));
		}
	}
}

3,结果按队列先进先出,与前面get顺序保持一致,显示如下:

["3","4"]