我希望我的 Spring Boot 应用程序对 Postgres 数据库进行的 JPA 查询在 5 秒后超时。
我创建了这个 20 秒的查询来测试超时:
@Query(value = "select count(*) from pg_sleep(20)", nativeQuery = true)
int slowQuery();
我在 application.config
中设置了以下属性:
spring.jpa.properties.javax.persistence.query.timeout=3000
javax.persistence.query.timeout=5000
但查询在3s或5s后并没有超时(仍然需要20s才能执行)。
奇怪的是,如果我用 @Transactional(timeout = 10)
注释 slowQuery
,它会在 10 秒左右后超时。
我不希望对每个查询都进行注释。我正在使用 JPA 2.0 和 Tomcat 连接池。
仅仅通过在应用程序属性文件中设置它们来使超时工作需要什么魔法?
最佳答案
要使超时通用,在您的 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;
}
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;
}
关于java - JPA 查询超时参数被忽略,但 @Transaction 注释有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53827071/