MySQL社区

 找回密码
 注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

搜索
查看: 1933|回复: 4
打印 上一主题 下一主题

关于事务中更新后不生效问题

[复制链接]
跳转到指定楼层
1#
发表于 2016-1-14 16:37:24 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
我们在做一个抽奖系统中,每个用户只有一次抽奖机会,由于采用多实例部署,所以要对每次抽奖操作加锁,且判断用户是否有抽奖机会。在用户并发大的时候会出现用户进行了两次抽奖。并且间隔时间都有几分钟。具体代码如下:
@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;
}
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
收藏收藏 分享淘帖 顶 踩
2#
 楼主| 发表于 2016-1-14 16:40:33 | 只看该作者
采用spring+mybatis,日志显示,在两次wechatMapper.updateLotteryFinish的返回都是1,可以确定用户的抽奖次数为1,SQL代码如下:
  <!--用户抽奖次数减少 -->
  <update id="updateLotteryFinish" parameterType="int">
        update fd_wechat set remain_time = remain_time-1,finish_time=finish_time+1
        where wechat_id = #{wechatId,jdbcType=INTEGER} and remain_time > 0;
  </update>

所以怀疑第一次update根本没有成功。但是日志显示第一次整个方法完整的执行完成,没有异常也没有回滚。
3#
 楼主| 发表于 2016-1-14 16:40:58 | 只看该作者
这究竟是个什么鬼呢,有哪位大拿可以帮忙分析一下。
4#
 楼主| 发表于 2016-1-15 08:39:07 | 只看该作者
发现一个问题,在update前面加一个select似乎可以解决
5#
发表于 2016-1-15 16:04:06 | 只看该作者
Pumaly 发表于 2016-1-15 08:39
发现一个问题,在update前面加一个select似乎可以解决


您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|申请友链|小黑屋|Archiver|手机版|MySQL社区 ( 京ICP备07012489号   
联系人:周生; 联系电话:13911732319

GMT+8, 2024-6-18 20:25 , Processed in 0.137144 second(s), 23 queries , Gzip On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表