在Spring框架中使用超时属性有什么好处?

What are the advantages of using timeout property in Spring framework?

当我阅读有关事务的 this 教程时,我注意到 timeout 属性,这是我以前从未在我开发的任何 REST 服务中使用过的。

例如,在这段代码中:

@Service
@Transactional(
  isolation = Isolation.READ_COMMITTED, 
  propagation = Propagation.SUPPORTS, 
  readOnly = false, 
  timeout = 30)
public class CarService {
 
    @Autowired
    private CarRepository carRepository;
 
    @Transactional(
      rollbackFor = IllegalArgumentException.class, 
      noRollbackFor = EntityExistsException.class,
      rollbackForClassName = "IllegalArgumentException", 
      noRollbackForClassName = "EntityExistsException")
    public Car save(Car car) {
        return carRepository.save(car);
    }
}

使用timeout属性有什么好处或优势?使用它是一种好习惯吗?谁能告诉我超时的用例 属性?

  1. 一个是防止记录被长时间锁定而无法满足任何其他请求。

  2. 假设您正在订票。在最终提交页面上,它说了这么久,你的用户会永远等待吗?所以你设置了http客户端超时。但是现在你有 http 客户端超时,如果你没有事务超时会发生什么?您向用户显示错误说它没有成功,但您的交易需要时间,因为它没有任何超时并在您的 http 客户端超时后提交。

Spring Docs解释:

Timeout enables client to control how long the transaction runs before timing out and being rolled back automatically by the underlying transaction infrastructure.

因此,好处显而易见 - 控制事务(及其下的查询)可能持续多长时间,直到它们被回滚。

问:为什么控制交易时间是useful/good?

A: If you are deliberately expecting your transaction not to take too long - it's a good time to use this configuration; if you're expecting that your transaction might take longer than its default maximum time, it is, agian, helpful to provide this configuration.

以上答案全部正确,但需要注意的是:

this property exclusively designed for use with Propagation.REQUIRED or Propagation.REQUIRES_NEW since it only applies to newly started transactions.

如文档所述。