- 积分
- 21
- UID
- 20871
- 阅读权限
- 10
- 注册时间
- 2016-1-14
- 精华
- 在线时间
- 小时
- 最后登录
- 1970-1-1
- 职业
- 1
|
我们在做一个抽奖系统中,每个用户只有一次抽奖机会,由于采用多实例部署,所以要对每次抽奖操作加锁,且判断用户是否有抽奖机会。在用户并发大的时候会出现用户进行了两次抽奖。并且间隔时间都有几分钟。具体代码如下:
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public synchronized LotteryGift[] doLotteryGift(Wechat wechat, String ip) throws Exception {
LotteryGift gift0 = null;// 主奖
LotteryRecord lotteryRecord0 = null;
LotteryGift gift1 = null;// 副奖2
LotteryRecord lotteryRecord1 = null;
LotteryGift gift2 = null;// 副奖2
LotteryRecord lotteryRecord2 = null;
LotteryGift gift3 = null;// 主奖
LotteryRecord lotteryRecord3 = null;
long startTime = System.currentTimeMillis();
// 加锁 每次只允许一个实例抽奖
SystemParamter systemParamter = new SystemParamter();
systemParamter.setId(1);
systemParamter.setSysValue(String.valueOf(System.currentTimeMillis()));
systemParamterMapper.updateByPrimaryKey(systemParamter);
// 更新抽奖机会
int cnt = wechatMapper.updateLotteryFinish(wechat.getWechatId());
if( cnt <= 0)
throw new Exception("wechatId:" + wechat.getWechatId() + " openId:"
+ wechat.getOpenId() + " updateLotteryFinish cnt:"+cnt+ "没有抽奖机会....");
logger.error("wechatId:" + wechat.getWechatId() + " openId:" + wechat.getOpenId()
+ " updateLotteryFinish cnt:"+cnt+" start lottery....");
....省略具体抽奖细节
LotteryGift[] retGift = { gift0, gift1, gift2, gift3 };
long endTime = System.currentTimeMillis();
logger.error("wechatId:" + wechat.getWechatId() + " openId:" + wechat.getOpenId()
+ " finish lottery,giftId:" + (gift0 == null ? "" : gift0.getGiftId())
+ " " + (gift1 == null ? "" : gift1.getGiftId()) + " "
+ (gift2 == null ? "" : gift2.getGiftId()) + " "
+ (gift3 == null ? "" : gift3.getGiftId()) + " use Time:"+(endTime-startTime));
return retGift;
}
|
|