我使用Spring啓動,並試圖做畝存儲庫的findAll查詢應返回結果的流:春JpaRepository的findAll,Java的8個流,連接已被放棄
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[[email protected]]: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()) {
作爲每文檔,採用ST時在JpaRepositories中,你應該總是在使用後關閉它們。由於它們實現了AutoCloseable,因此您可以使用try和resources塊。 http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-streaming
甲流潛在地封裝底層數據存儲特定資源和使用後必須因此被關閉。您可以使用close()方法手動關閉流,也可以使用Java 7 try-with-resources塊。
在文檔中甚至有一個例子與我做的完全一樣。所以我正在做所有的文件說,據我所知,但我仍然在手術後30秒出現異常。顯然,這個連接並沒有關閉,而是一直懸掛起來。爲什麼是這樣的,我怎麼能克服這一點?
我試過用Postgres 9.5和MariaDB作爲數據庫。我使用的是通過彈簧啓動的性能配置類似,最新的可能連接器/驅動器和Tomcat的連接池:
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
我確定它會返回List和Page。我不確定它是否返回流。隨你。您是否寫了如下注釋:@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME),@Service並且您是否擁有DataSource Beans,Repository Beans,ServiceBeans的Creators(@Configuration)? – LowLevel
是的。我所有的註釋和bean都設置好了。如果他們不會被設置,那麼我的數據庫的東西根本不會工作,但它確實很好。只是這個令人討厭的廢棄連接錯誤,我不喜歡在我的日誌中。這只是一個簡單的例子。如果您查看我提供的文檔鏈接,那麼您將看到Spring 8和Java 8的JPA除了支持Page和Collection之外,還支持Stream。爲什麼我使用流而不是頁或集合的動機是MyThings的集合可能是巨大的,我不能將它讀到內存中。 – Tarmo
如果您嘗試獲取名單,你知道嗎? –
LowLevel