Spring transaction mining pit - timeout

Problem Description

When using Spring transactions, the timeout limit is added, @Transactional(timeout = 10), and it is found that the transaction will not be rolled back due to timeout.

Function description

The so-called transaction timeout refers to the maximum time allowed for a transaction to execute. If the time limit is exceeded but the transaction has not been completed, the transaction will be automatically rolled back. In the TransactionDefinition, the timeout period is represented by an int value, and its unit is seconds.
The default setting is the timeout value of the underlying transaction system. If the underlying database transaction system does not set a timeout value, then it is none, and there is no timeout limit.

problem causes

Spring transaction timeout = the time from the start of the transaction to the creation of the last Statement + the timeout time for the execution of the last Statement (that is, its queryTimeout). Therefore, the transaction cannot be rolled back after the timeout outside the execution of the Statement.

Solution

for example

@Transactional(timeout = 2, rollbackFor = Exception.class,isolation = Isolation.DEFAULT)
  public void createOrder(Integer userId, Integer goodsId, Integer amount) throws Exception {
      //减少库存
      int result = goodsDao.updateGoodsStock(goodsId, amount);
      if (result != 1) {
          throw new Exception("创建订单失败");
      }
      //制造异常
//        int i = 1/0;
      //插入订单
      orderDao.insert(userId, goodsId, amount);
      Thread.sleep(3000);
  }

In the piece of code, if you put Thread.sleep(3000); at the end, it will not roll back. So pay special attention when developing. If there is really a particularly important operation (after the last Statement), my current solution is to
*try to execute the middle of the Statement
* and add an unrelated lightweight Statement operation at the end of the operation

principle

I have time to look at it, it must be in Spring AOP

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326107326&siteId=291194637