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

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

}

先减库存再查库存;库存量小于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中的更新无法进行,处于等待状态(体现了事务的隔离性)

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