在controller类中lock
private static final ReentrantLock lock = new ReentrantLock(false);
@RequestMapping(value = "/")
private String index(HttpServletRequest request) {
return "index";
}
@RequestMapping(value = "/purchase")
public String purchase(){
try{
lock.lock();
String msg = syncXyUserService.purchase();
return msg;
}catch (Exception e){
log.error("程序出现异常");
}finally {
lock.unlock();
}
return "购物失败";
}
purchase对应的类上加事物注解@Transactional
public String purchase() {
String msg = "";
try{
Product product = productDao.findById(1L).orElse(null);
Integer leave = product.getLeave();
if(leave == 0){
msg = Thread.currentThread().getName() + ":购买失败";
log.error(Thread.currentThread().getName() + ":购买失败");
}else{
leave = leave - 1;
product.setLeave(leave);
productDao.update(product,true);
msg = Thread.currentThread().getName() + ":购买成功,剩余" + leave;
log.info(Thread.currentThread().getName() + ":购买成功,剩余" + leave);
}
}catch (Exception e){
log.error("程序出错啦");
}finally {
}
return msg;
}