springboot項目如果在service層上同時使用@Transactional與synchronized失效
例如:
@Service @Transactional public class OrderServiceImpl implements OrderService { @Override public synchronized int update(Integer id) { ...
...
... } }
失效原因:
synchronized代碼塊里執行的內容是在事務里面,在事務commit前可能有多個線程進入代碼塊,導致讀取的數據都是一致的,不是更新后的
解決辦法:在service層去掉@Transactional注解或將synchronized寫在controller層
@RestController @RequestMapping("order") public class StockController { @Autowired private OrderService orderService; @GetMapping("/update") public String update(Integer id){ synchronized (this) { int orderId = orderService.kill(id); return ""; } }