关于redis的pipline和lua脚本

44 篇文章 4 订阅
12 篇文章 1 订阅

1.     关于redis命令执行方式的一点看法:

Redis命令执行时是串行的,在同一个连接上客户端发送一条命令,redis对这个命令进行操作然后返回结果,客户端只有接到这个结果之后才能发送下一条命令,例如:

 

如此串行的执行方式效率非常低,为此,redis引入了pipline,它可以让客户端依次发送一批命令过期,然后redis依次执行这些命令,并把这些命令的结果依次放入到一个list<object>里面一次返回给客户端,引入pipline之后,就可以在执行多条命令时减少redis客户端和redis服务端之间的网络交互次数,此时pipline里命令的执行过程就变成下面这样了:

由上面的描述可以看到,引入pipline之后,降低了多次命令-应答之间的网络交互次数,并不能缩小redis对每个命令的处理时间。

2.     那么什么时候使用pipline?什么时候使用lua呢

   当多个redis命令之间没有依赖、顺序关系(例如第二条命令依赖第一条命令的结果)时,建议使用pipline;如果命令之间有依赖或顺序关系时,pipline就无法使用,此时可以考虑才用lua脚本的方式来使用;

3.注意:

(1)Redis无法提供类似数据库那种具备ACID特性的事务操作,可以基本确认引入redis就一定无法保证操作的ACID特性;因此,在咱们开发过程中,要考虑实际的应用场景,如果场景本身对ACID特性要求不那么强烈就可以考虑引入reids,否则,就只能使用数据库;

(2)能不采用lua就尽量不要采用lua

4.关于redis使用的pipline例子

private ResultStr getFullMomentFromRedis(long callIndex, String userID, String momentId)
   {
      String logFlag = "DataProxy.getFullMomentFromRedis";
      //获取redis分片
      JedisClient jedisClient = m_dataCenter.getJedisClient(callIndex, momentId);
      if (jedisClient == null)
      {
          m_logger.error(String.format("[ci:%d]<%s>get jedis client by %s from data center fail", callIndex, logFlag, momentId));
          return new ResultStr(ThriftResult.NO_CONTENT, null);
      }
      // 程序走的这里,说明已经从redis中获userID.mt中获取到了动态的部分信息,剩下的评论、点赞等信息继续获取
      JSONObject aMomentInfo = null;

      // 使用pipline一次从redis中获取剩下的点赞,评论,映射关系等信息
      JedisClientPipline pipline = jedisClient.getPipline(callIndex);
      // 第1个要获取的信息是动态内容
      pipline.hget(userID + ".mt", momentId);
      // 第2个要获取的信息是动态和frepp映射关系
      pipline.get(momentId);
      // 第3个要获取的信息是动态的点赞
      pipline.zrevrange(momentId + ".like", 0, -1);
      // 第4个要获取的信息是动态的评论
      pipline.hgetAll(momentId + ".ct");

      // 获取pipline返回的结果,并将所用Jedis连接返回给连接池
      List<Object> piplineRes = pipline.syncAndReturnAll(false);
      
      //处理获取的第1项结果,动态内容
      if (piplineRes.get(0) != null && (piplineRes.get(0) instanceof String))
      {
          aMomentInfo = Utils.str2Json((String)piplineRes.get(0));// 将从frepp.mt中获取到的部分动态信息解析成JSON串
      }
      if (aMomentInfo == null)
      {
          m_logger.warn(String.format("[ci:%d][%s] fail! cann't parse string : %s to a JSON Object", callIndex, logFlag, (String)piplineRes.get(0)));
          return new ResultStr(ThriftResult.NO_CONTENT, null);
      }
      // 处理获取的第2项结果:动态和frepp的映射关系
      if (piplineRes.get(1) != null && (piplineRes.get(1) instanceof String))
      {
          JSONObject joMap = Utils.str2Json((String) piplineRes.get(1));
          if (joMap != null)
          {
             aMomentInfo.put("isvd", joMap.getBoolean("isvd"));
             aMomentInfo.put("userID", joMap.getLongValue("userID"));

          }
          else
             m_logger.warn(String.format("[ci:%d]<%s> fail! change String(moment->frepp) to JSON fail! String :%s", callIndex, logFlag,
                   piplineRes.get(1)));
      }

      // 处理获取的第3项结果:点赞的相关信息
      if (piplineRes.get(2) != null && (piplineRes.get(2) instanceof Set))
      {
          @SuppressWarnings("unchecked")
          Set<String> likers = (Set<String>) piplineRes.get(2);
          if (likers != null && likers.size() > 0)
             aMomentInfo.put("lks", piplineRes.get(2));
      }

      // 处理获取的第4项结果:评论的相关信息
      if (piplineRes.get(3) != null && (piplineRes.get(3) instanceof Map))
      {
          @SuppressWarnings("unchecked")
          Map<String, String> comments = (Map<String, String>) piplineRes.get(3);
          Set<String> commentIds = comments.keySet();
          JSONArray jaCommentList = new JSONArray();
          for (String aCommentId : commentIds)
          {
             String commentContent = comments.get(aCommentId);
             JSONObject joComment = Utils.str2Json(commentContent);
             if (joComment != null)
             {
                joComment.put("ctid", aCommentId);
                jaCommentList.add(joComment);
             }
             else
                m_logger.warn(String.format("[ci:%d]<%s> fail! change comment content to JSON fail! comment content :%s", callIndex, logFlag, commentContent));
          }
          if (jaCommentList.size() > 0)
             aMomentInfo.put("cts", jaCommentList);
      }
      
      // 设置userID和mtid字段
      aMomentInfo.put("mtid", Long.parseLong(momentId));
      return new ResultStr(ThriftResult.SUCCESS, aMomentInfo.toJSONString());
   }

下面是对redis的pipline相关操作的封装:

public class JedisClientPipline
	{
		private Pipeline m_pipline = null;
		Jedis m_jds = null;
		JedisPool m_jedisPool = null;
		public JedisClientPipline(JedisPool jedisPool, Jedis jds, Pipeline p)
		{
			m_pipline = p;
			m_jds = jds;
			m_jedisPool = jedisPool;
		}
		
		public boolean get(String key)
		{
			if(m_pipline == null)
				return false;
			m_pipline.get(key);
			return true;
		}
		
		public boolean hget(String key, String field)
		{
			if(m_pipline == null)
				return false;
			m_pipline.hget(key, field);
			return true;
		}
		
		public boolean zrevrange(String key, long start, long end)
		{
			if(m_pipline == null)
				return false;
			m_pipline.zrevrange(key, start, end);
			return true;
		}
		
		public boolean hgetAll(String key)
		{
			if(m_pipline == null)
				return false;
			m_pipline.hgetAll(key);
			return true;
		}
		
		/**
		 * @param boolean isBad 表示当前的管道所在的jedis连接是否坏掉
		 * */
		public List<Object> syncAndReturnAll(boolean isBad)
		{
			List<Object> res = null;
			try
			{
				if (m_pipline != null)
					res = m_pipline.syncAndReturnAll();
			}
			catch (Exception ex)
			{
				isBad = true;
			}
			//将jedis连接换到连接池中
			if(isBad)
				m_jedisPool.returnBrokenResource(m_jds);
			else
				m_jedisPool.returnResource(m_jds);
			
			return res;
		}
	}



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值