首页 > 解决方案 > jdbctemplate 不关闭连接

问题描述

我有一些代码

@Bean("jdbc")
public JdbcTemplate jdbc(@Qualifier("dataSource") DataSource ds) {
    return new JdbcTemplate(ds);
}

@Bean("dataSource")
public DataSource dataSource(Environment environment) {
    JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
    String jndiName = environment.getProperty("dbconnection.jndiName", DEFAULT_DATASOURCE_JNDI_NAME);
    try {
        return dataSourceLookup.getDataSource(jndiName);
    } catch (DataSourceLookupFailureException e) {
        PGSimpleDataSource dataSource = new PGSimpleDataSource();
        dataSource.setDatabaseName(environment.getProperty("dbconnection.dbname"));
        dataSource.setURL(environment.getProperty("dbconnection.url"));
        dataSource.setUser(environment.getProperty("dbconnection.username"));
        dataSource.setPassword(environment.getProperty("dbconnection.password"));
        dataSource.setCurrentSchema(environment.getProperty("dbconnection.dbschema"));
        return dataSource;
    }
}   

现在,在自定义存储库方法(只读)中使用 jdbcTemplate,返回列表对象

 Connection connection = null;
    try {
        connection = jdbcTemplate.getDataSource().getConnection();
        return findByParamsJdbc(arg1, arg2, arg3,
                arg4, arg5,
                arg6, arg7, arg8, arg9,
                arg10, arg11, arg12, connection);
    } catch (Exception e) {
        if (Objects.nonNull(connection)) {
            connection.close();
        }
    } finally {
        if (Objects.nonNull(connection)) {
            if (!connection.isClosed()) {
                connection.close();
            }
        }
    }
    throw ex999();

在 findByParamsJdbc 里面有各种preparedStatement,'connection.createArrayOf'等

一段时间后,应用程序崩溃,服务器 CPU 99% 已加载

内存转储显示jdbcTemplate没有关闭连接,每次都打开一个新的,为什么会这样?

班级名称 | 浅堆 | 保留堆 | 百分比

org.hibernate.internal.SessionFactoryImpl @ 0x5c438a130 | 136 | 74,883,816 | 29.72% |- org.hibernate.engine.query.spi.QueryPlanCache @ 0x5c4c0b658 | 32 | 70,764,832 | 28.08% |- org.hibernate.jpa.event.spi.JpaIntegrator @ 0x5c48177c8 | 24 | 362,856 | 0.14% |- org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl @ 0x5c48a2cc8 | 56 | 293,208 | 0.12% |- org.hibernate.persister.entity.SingleTableEntityPersister @ 0x5c43e3590 | 第552章 235,176 | 0.09% |- org.hibernate.service.internal.SessionFactoryServiceRegistryImpl @ 0x5c4812e80| 56 | 182,936 | 0.07% |- org.hibernate.persister.entity.SingleTableEntityPersister @ 0x5c4535518 | 第552章 119, 416 | 0.05% |- org.hibernate.persister.entity.SingleTableEntityPersister @ 0x5c455d680 | 第552章 118,736 | 0.05% |- org.hibernate.persister.entity.SingleTableEntityPersister @ 0x5c45697d8 | 第552章 117,576 | 0.05%

标签: javaspringhibernatewildflyjdbctemplate

解决方案


推荐阅读