商品购买(考虑并发问题,需要考虑事务的隔离级别)

controller层
package cn.kooun.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.kooun.pojo.jpa.NotCheckOnline;
import cn.kooun.pojo.params.ItemBuyItemParam;
import cn.kooun.service.ItemService;

/**
 *  商品controller
 * @author HuangJingNa
 * @date 2019年12月24日 下午2:23:56
 *
 */
@RestController
@RequestMapping("item")
public class ItemController {
    @Autowired
    private ItemService itemService;
    /**
     *  商品购买
     * @author HuangJingNa
     * @date 2019年12月24日 下午2:26:00
     *
     * @param itemBuyItem
     * @return
     */
    @GetMapping("buy_item")
    @NotCheckOnline//为了方便测试,此处就不校验用户是否在线
    public Object buyItem(@Validated ItemBuyItemParam itemBuyItemParam) {
        return itemService.buyItem(itemBuyItemParam);
    }
}
商品购买接口参数类ItemBuyItemParam,使用@Validated注解进行数据校验
package cn.kooun.pojo.params;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 *  商品购买接口参数
 * @author HuangJingNa
 * @date 2019年12月24日 下午2:27:48
 *
 */
@Getter
@Setter
@ToString
public class ItemBuyItemParam {
    /**商品id*/
    @NotBlank(message = "系统繁忙,请联系管理员~")
    private String itemId;
    /**商品购买数量*/
    @NotNull(message = "商品购买数量不能小于1")
    @Min(value = 1, message = "商品购买数量不能小于1")
    private Long itemCount;
}
service层(错误的写法)
  • 由于考虑到并发的情况,需要用到事务回滚(默认对增删改进行隔离操作)
  • 且并发的时候,查询是不隔离的,若先查,则会出现获取的是相同数据
  • 但减库存的时候,又是按照MySQL中提交事务了才释放锁(出现了等待)
  • 查询的数据一直减客户端赋给的值,这时候就会出现负数
  • 因此,先减库存,再去查库存;若查出的库存量<0,则利用抛出异常来回滚事务,让数据库恢复原状
package cn.kooun.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.kooun.common.result.ResultUtils;
import cn.kooun.mapper.ItemMapper;
import cn.kooun.pojo.params.ItemBuyItemParam;
/**
 *  商品service
 * @author HuangJingNa
 * @date 2019年12月24日 下午2:31:55
 *
 */

@Service
public class ItemService {
    @Autowired
    private ItemMapper itemMapper;
    /**
     *  商品购买(错误写法,没有考虑到并发的情况)
     * @author HuangJingNa
     * @date 2019年12月24日 下午2:32:25
     *
     * @param itemBuyItemParam
     * @return
     */
    public Object buyItem(ItemBuyItemParam itemBuyItemParam) {
        Long itemCount = itemBuyItemParam.getItemCount();
        //根据商品id查询商品的库存量
        Long countDB = itemMapper.findItemCountByItemId(itemBuyItemParam.getItemId());
        if(itemCount > countDB) {
            return ResultUtils.error("没有库存了,请联系卖家~");
        }
        //根据商品id更新该商品的库存
        Long flag = itemMapper.updateItemCountByItemId(
                itemBuyItemParam.getItemId(),
                itemBuyItemParam.getItemCount());
        if(flag < 0) {
            return ResultUtils.error("系统繁忙,请稍后重试~");
        }
        //返回友好提示,购买成功
        return ResultUtils.success("购买成功~");
    }

}
dao层
package cn.kooun.mapper;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 *  商品mapper
 * @author HuangJingNa
 * @date 2019年12月24日 下午2:35:14
 *
 */
public interface ItemMapper {
    /**
     *  根据商品id查询商品的库存量
     * @author HuangJingNa
     * @date 2019年12月24日 下午2:44:10
     *
     * @param itemId
     * @return
     */
    @Select("SELECT" + 
            "   i.count itemCount" + 
            " FROM" + 
            "   i_item i" + 
            " WHERE" + 
            "   i.id = #{itemId}")
    Long findItemCountByItemId(@Param("itemId")String itemId);
    /**
     *  根据商品id更新该商品的库存
     * @author HuangJingNa
     * @date 2019年12月24日 下午2:44:41
     *
     * @param itemId
     * @param itemCount
     * @return
     */
    @Update("UPDATE i_item i" + 
            " SET i.count = i.count - #{itemCount}" + 
            " WHERE" + 
            "   i.id = #{itemId}")
    Long updateItemCountByItemId(
            @Param("itemId")String itemId, 
            @Param("itemCount")Long itemCount);

}

service层开始事务,并且考虑到并发情况:先减库存再查库存;库存量小于0,则需要事务回滚(通过抛异常的方法,将数据库还原到未执行前的状态)——正确写法

package cn.kooun.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.kooun.common.result.ResultUtils;
import cn.kooun.mapper.ItemMapper;
import cn.kooun.pojo.exception.ItemCountException;
import cn.kooun.pojo.params.ItemBuyItemParam;
/**
 *  商品service
 * @author HuangJingNa
 * @date 2019年12月24日 下午2:31:55
 *
 */

@Service
//通过抛异常给全局异常处理器处理来回滚事务
@Transactional(rollbackFor = Exception.class)
public class ItemService {
    @Autowired
    private ItemMapper itemMapper;
    
    /**
     *  商品购买(正确写法)
     * @author HuangJingNa
     * @date 2019年12月24日 下午2:32:25
     *
     * @param itemBuyItemParam
     * @return
     * @throws Exception 
     */
    public Object buyItem(ItemBuyItemParam itemBuyItemParam) throws Exception {
        //根据商品id更新该商品的库存(减库存)
        Long flag = itemMapper.updateItemCountByItemId(
                itemBuyItemParam.getItemId(),
                itemBuyItemParam.getItemCount());
        if(flag < 0) {
            return ResultUtils.error("系统繁忙,请稍后重试~");
        }
        //减完库存之后,进行查询
        Long countDB = itemMapper.findItemCountByItemId(itemBuyItemParam.getItemId());
        //若库存小于0,则通过抛出异常来回滚事务
        if(countDB < 0) {
            throw new ItemCountException("购买失败,该商品的库存不足~");
        }
        //若库存不小于0,则返回友好提示,购买成功
        return ResultUtils.success("购买成功~");
    }

}
自定义库存异常类
package cn.kooun.pojo.exception;
/**
 *  库存异常处理
 * @author HuangJingNa
 * @date 2019年12月24日 下午3:07:41
 *
 */
public class ItemCountException extends Exception {

    private static final long serialVersionUID = -7847571970908888139L;

    public ItemCountException() {
        super();
    }

    public ItemCountException(String message) {
        super(message);
    }
    
}
全局异常处理
package cn.kooun.core.exception;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.kooun.common.result.Result;
import cn.kooun.common.result.ResultUtils;
import cn.kooun.pojo.exception.ItemCountException;
import cn.kooun.pojo.exception.OffLineException;

/**
 *  全局异常处理
 * @author HuangJingNa
 * @date 2019年12月21日 下午3:46:19
 *
 */
@ControllerAdvice//标记此类为全局异常拦截器
public class GlobalExceptionHandler {
    /**
     *  系统异常处理,如404、500
     * @author HuangJingNa
     * @date 2019年12月21日 下午3:48:45
     *
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)//监听对应的异常对象
    @ResponseBody
    public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception{
        //控制台输出错误信息
        e.printStackTrace();
        if(e instanceof OffLineException) {
            return ResultUtils.error("登录失效,请重新登录~", Result.JUMP_LOGIN);
        }
        if(e instanceof ItemCountException) {
            return ResultUtils.error(e.getMessage());
        }
        return ResultUtils.error("系统繁忙,请联系管理员~");
    }
    /**
     *  自定义异常处理@Validated抛出的数据校验
     * @author HuangJingNa
     * @date 2019年12月21日 下午3:54:32
     *
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Object defaultArithmeticHandler(HttpServletRequest req, BindException e) throws Exception{
        //控制台输出错误信息
        e.printStackTrace();
        return ResultUtils.error(
                e.getBindingResult().getFieldError().getDefaultMessage(), 
                "BindException");
    }
}
测试

通过打断点的方式来进行模拟事务未提交状态,浏览器输入网址:localhost:9001/item/buy_item?itemId=1&itemCount=1
且navicat也进行库存更新
以上就可以模拟多条线程的情况下,不提交事务是,navicat中的更新无法进行,处于等待状态(体现了事务的隔离性)

通过打断点的方式演示事务未提交完成,数据库的更改操作无法进行,处于等待.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270