返回Java 8流的Spring存储库方法不会关闭JDBC连接
我有一个Spring data
信息库:
@Repository
interface SomeRepository extends CrudRepository<Entity, Long> {
Stream<Entity> streamBySmth(String userId);
}
我正在某些Spring bean中调用该方法:
I am calling that method in some Spring bean:
@Scheduled(fixedRate = 10000)
private void someMethod(){
someRepository.streamBySmth("smth").forEach(this::callSomeMethod);
}
我正在使用MySQL数据库.当我在成功的方法调用后运行应用程序时,它将引发异常:
I am using MySQL database. And when I am running application after some successful method invocations it throws an exception:
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 08001
o.h.engine.jdbc.spi.SqlExceptionHelper : Could not create connection to database server.
o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task.
org.springframework.dao.DataAccessResourceFailureException: Unable to acquire JDBC Connection; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
看来,Spring没有正确关闭连接.如果我将方法的返回值从Stream
更改为List
,则它可以正常工作.
It seems, that connection was not closed properly by Spring. If I have changed method return value to List
from Stream
it works correctly.
更新: Spring Boot版本是1.4.1.RELEASE
UPDATE: Spring Boot version is 1.4.1.RELEASE
As the reference documentation clearly states, Stream
s need to be used with a try-with-resources block.
此外,通过用@Transactional
注释周围的方法,确保在消耗流时保持(只读)事务处于打开状态.否则,将应用默认设置,并尝试在返回存储库方法时释放资源.
Also, make sure you keep a (read-only) transaction open for the time of the consumption of the stream by annotating the surrounding method with @Transactional
. Otherwise the default settings apply and the resources are attempted to be freed on repository method return.
@Transactional
public void someMethod() {
try (Stream<User> stream = repository.findAllByCustomQueryAndStream()) {
stream.forEach(…);
}
}