redis抢购实现关键代码
在使用redis的时候如果redisTemplate.execute方法执行多条redis命令,则会出现资源无法释放的问题,如果改成redisTemplate.executePipelined则不会出现;
/** * 更新用户信息并将股票余数减1 * * @param ppkey * 队列key:set+mobile * @param upkey * 股票余数 * @param rushuser * @return */ protected boolean updateUserAndDecrStock(final String ppkey, final String upkey, final RushUser rushuser) { boolean flag = false; try { redisTemplate.executePipelined(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { byte[] upkeyb = redisTemplate.getStringSerializer().serialize(upkey); byte[] stockKey = redisTemplate.getStringSerializer().serialize(RedisCounterEnum.STOCK_COUNT.getCounterName());// 股权证编号(抢购成功时记录,从1开始递增) byte[] ppkeyb = redisTemplate.getStringSerializer().serialize(ppkey); connection.watch(upkeyb, stockKey); connection.multi(); Object counter = redisTemplate.opsForValue().get(upkey); Object stockNoObject = redisTemplate.opsForValue().get(RedisCounterEnum.STOCK_COUNT.getCounterName()); int count = Integer.valueOf(counter == null ? "0" : counter.toString()); int stock = Integer.valueOf(stockNoObject == null ? "0" : stockNoObject.toString()); if (count > 0) { connection.decr(upkeyb); String stockNo = (stock + 1) + ""; rushuser.setStockno(stockNo);// 设置股权证编号 String value = ZGUtil.objectToJson(rushuser); connection.set(stockKey, redisTemplate.getStringSerializer().serialize(stockNo)); connection.set(ppkeyb, redisTemplate.getStringSerializer().serialize(value)); } connection.exec(); return null; } }); flag = true; } catch (Exception e) { logger.error(e.getMessage(), e); flag = false; } return flag; }
相关推荐
王道革 2020-11-25
wangdonghello 2020-11-03
Langeldep 2020-11-16
chenhualong0 2020-11-16
聚合室 2020-11-16
koushr 2020-11-12
MRFENGG 2020-11-11
guoyanga 2020-11-10
fackyou00 2020-11-10
Orangesss 2020-11-03
dongCSDN 2020-10-31
rainandtear 2020-10-30
Quietboy 2020-10-30
liuyulong 2020-10-29
fansili 2020-10-29
温攀峰 2020-10-23
jackbon 2020-10-19
kaixinfelix 2020-10-04