JPA 查询超时参数被忽略但 @Transaction 注释有效

ixe*_*013 6 java spring timeout jpa jpa-2.0

我希望 Spring Boot 应用程序对 Postgres 数据库进行的 JPA 查询在 5 秒后超时。

我创建了这个 20 秒查询来测试超时:

@Query(value = "select count(*) from pg_sleep(20)", nativeQuery = true)
int slowQuery();
Run Code Online (Sandbox Code Playgroud)

我在 中设置了以下属性application.config:

spring.jpa.properties.javax.persistence.query.timeout=3000
javax.persistence.query.timeout=5000
Run Code Online (Sandbox Code Playgroud)

但是查询在 3s 或 5s 后不会超时(执行仍然需要 20s)。

奇怪的是,如果我注释slowQuery用@Transactional(timeout = 10),超时后10秒左右。

我不想注释每个查询。我正在使用 JPA 2.0 和 Tomcat 连接池。

仅通过在应用程序属性文件中设置它们就可以使超时工作需要什么魔法?

Fra*_*cio 6

为了使超时通用,在您的 JpaConfiguration 中,当您声明 PlatformTransactionManager Bean 时,您可以设置事务的默认超时:

@Bean
public PlatformTransactionManager transactionManager() throws Exception {
    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory().getObject());
    txManager.setDataSource(this.dataSource);
    txManager.setDefaultTimeout(10); //Put 10 seconds timeout
    return txManager;
}
Run Code Online (Sandbox Code Playgroud)

PlatformTransactionManager 继承 AbstractPlatformTransactionManager ,其中包含该方法:

    /**
     * Specify the default timeout that this transaction manager should apply
     * if there is no timeout specified at the transaction level, in seconds.
     * <p>Default is the underlying transaction infrastructure's default timeout,
     * e.g. typically 30 seconds in case of a JTA provider, indicated by the
     * {@code TransactionDefinition.TIMEOUT_DEFAULT} value.
     * @see org.springframework.transaction.TransactionDefinition#TIMEOUT_DEFAULT
     */
    public final void setDefaultTimeout(int defaultTimeout) {
        if (defaultTimeout < TransactionDefinition.TIMEOUT_DEFAULT) {
            throw new InvalidTimeoutException("Invalid default timeout", defaultTimeout);
        }
        this.defaultTimeout = defaultTimeout;
    }
Run Code Online (Sandbox Code Playgroud)