@Transactional與synchronized使用沖突問題


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 "";
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM