@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