你的位置:首页 > 软件开发 > 数据库 > Redis小实战分享

Redis小实战分享

发布时间:2016-04-15 00:00:25
看了很久博客园的博客,今天有点小冲动,写一个小小分享,欢迎吐槽,O(∩_∩)O哈哈~背景:微信活动小游戏开发,游戏中需要不断的恢复体力值,体力相关数据都存储在redis中。需求:1.当日首次登录,增加全部体力值;2.周期性增加定额体力值;实现方案1 ...

看了很久博客园的博客,今天有点小冲动,写一个小小分享,欢迎吐槽,O(∩_∩)O哈哈~

  • 背景:

微信活动小游戏开发,游戏中需要不断的恢复体力值,体力相关数据都存储在redis中。

  • 需求:

1.当日首次登录,增加全部体力值;

2.周期性增加定额体力值;

  • 实现方案1(全量更新):

出于用户量小、简单的考虑,对整个系统用户执行全量更新。

相关表:

 

 

体力

 

表名strength,前缀strength:uid:*,体力表,哈希存储

列名

备注

surplus

当前体力余量

 

total

体力总量

 

 

优化后代码如下:

 1 public boolean incrStrength(Long uid, int nums) { 2     boolean ret = false; 3     Jedis jedis = null; 4     // 用户体力表 5     String strgKey = "strength:uid:" + uid; 6     //体力时间表 7     String strgtimeline = "strgtimeline"; 8     long nowSecs = TimeUtil.toSecs(System.currentTimeMillis()); 9     try {10       jedis = YlcqUtil.getRedis().getReadPool().getResource();11       jedis.watch(strgKey);12       Transaction trans = jedis.multi();13       14       //获取当前体力15       List<String> strgInfo = jedis.hmget(strgKey, "surplus", "total");16       long surplus = Long.parseLong(strgInfo.get(0));17       long total = Long.parseLong(strgInfo.get(1));18       if(surplus == total){19         logger.info("体力值不能在增加!" + strgKey);20       }else{21         surplus = surplus + nums;22         if(surplus > total){23           surplus = total;24         }25         //更新体力26         jedis.hset(strgKey, "surplus", surplus + "");27         28         //插入体力时间29         jedis.zadd(strgtimeline, nowSecs, uid.toString());  30         List<Object> result = trans.exec();31         32         if (result == null || result.isEmpty()) {33           logger.debug("增加体力值失败!增加前:" + strgInfo + ";增加:" + nums);34         } else {35           ret = true;36         }37       }38     } catch (Exception e) {39       e.printStackTrace();40     } finally {41       YlcqUtil.getRedis().getReadPool().returnResource(jedis);42     }43     return ret;44   }

原标题:Redis小实战分享

关键词:Redis

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录