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;
	}

相关推荐