gpt4 book ai didi

java - Spring JpaRepository findAll、Java 8 Stream、Connection 已被放弃

转载 作者:行者123 更新时间:2023-12-02 16:16:12 25 4
gpt4 key购买 nike

我正在使用 Spring Boot 并尝试在 mu 存储库中执行 findAll 查询,该查询应返回结果流:

public interface MyThingRepository extends JpaRepository<MyThing, String> {
Stream<MyThing> findAll();
}

public class MyScheduledJobRunner {

@Autowired
private MyThingRepository myThingRepository;

public void run() {
try (Stream<MyThing> myThingsStream : myThingRepository.findAll()) {
myThingsStream.forEach(myThing -> {
// do some stuff
});
// myThingsStream.close(); // <- at one point even tried that, though the stream is wrapped in an auto-closing block. anyway, it did not help
System.out.println("All my things processed.");
}
System.out.println("Exited the auto-closing block.");
}
}

我得到的输出是:

All my things processed.
Exited the auto-closing block.
o.a.tomcat.jdbc.pool.ConnectionPool : Connection has been abandoned PooledConnection[com.mysql.jdbc.JDBC4Connection@2865b7d5]:java.lang.Exception
| at org.apache.tomcat.jdbc.pool.ConnectionPool.getThreadDump(ConnectionPool.java:1061)
...
at MyScheduledJobRunner.run(MyScheduledJobRunner:52)

MyScheduledJobRunner:52 是:

try (Stream<MyThing> myThingsStream : myThingRepository.findAll()) {

根据文档,在 JpaRepositories 中使用 Streams 时,您应该始终在使用后关闭它们。由于它们实现了 AutoCloseable,因此您可以将 try 与资源 block 一起使用。 http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-streaming

A Stream potentially wraps underlying data store specific resources and must therefore be closed after usage. You can either manually close the Stream using the close() method or by using a Java 7 try-with-resources block.

文档中甚至有一个示例,它的操作方式与我完全相同。因此,据我所知,我正在执行文档中所述的所有操作,但在操作后 30 秒我仍然收到异常。所以显然连接没有关闭并且处于挂起状态。这是为什么?我该如何克服这个问题?

我尝试过使用 Postgres 9.5 和 MariaDB 作为数据库。我正在使用最新的连接器/驱动程序和 Tomcat 连接池,它们是通过 Spring Boot 的属性配置的,如下所示:

spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/mydb?useSSL=false
username: user
password: password
initial-size: 10
max-active: 100
max-idle: 50
min-idle: 10
max-wait: 15000
test-while-idle: true
test-on-borrow: true
validation-query: SELECT 1
validation-query-timeout: 5
validationInterval: 30000
time-between-eviction-runs-millis: 30000
min-evictable-idle-time-millis: 60000
removeAbandonedTimeout: 60
remove-abandoned: true
log-abandoned: true

最佳答案

在池配置中您只需添加:“org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer”

关于java - Spring JpaRepository findAll、Java 8 Stream、Connection 已被放弃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37875481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com