我在5-6次请求后遇到错误。
org.springframework.dao.DataAccessResourceFailureException
Unable to acquire JDBC Connection; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
使用下面的代码可以正常工作,除了在几次请求后耗尽连接池。
我是Spring框架的新手,并使用在线示例编写了所有这些内容。我尝试了一些变种,都失败了。任何帮助,将不胜感激。感谢。
application.yml
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
dataSourceClassName: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
jdbcUrl: jdbc:mysql://localhost:3306/db_name?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=utf8
catalog: db_name
username: myusername
password: mypassword
testOnBorrow: true
validationQuery: SELECT 1
testWhileIdle: true
timeBetweenEvictionRunsMillis: 3600000
jpa:
show_sql: true
hibernate:
dialect: org.hibernate.dialect.MySQLDialect
show_sql: false
format_sql: true
connection:
provider_class: com.zaxxer.hikari.hibernate.HikariConnectionProvider
release_mode: after_transaction
...
ApplicationConfiguration.java
@Configuration
@PropertySource("classpath:application.yml")
@EnableTransactionManagement
@EnableSwagger2
@EntityScan("com...dal.data")
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@Configuration
@ConfigurationProperties(prefix="spring.datasource")
public class JpaConfig extends HikariConfig {}
@Autowired
private JpaConfig jpaConfig;
@Bean(destroyMethod = "close")
public DataSource dataSource() {
return new HikariDataSource(jpaConfig);
}
@Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder factoryBuilder = new LocalSessionFactoryBuilder(dataSource());
factoryBuilder.addAnnotatedClasses(
com...dal.data.MyEntity.class, ...
);
return factoryBuilder.buildSessionFactory();
}
TestDaoImpl.java
@Repository
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TestDaoImpl implements TestDao {
private static final Logger logger = LoggerFactory.getLogger(TestDaoImpl.class);
@PersistenceContext
private EntityManager em;
@SuppressWarnings("unchecked")
@Override
public List<MyEntity> getEntities() {
return em.unwrap(Session.class)
.createCriteria(MyEntity.class, "myEntity")
.list();
}
@Override
@Transactional
public void saveTest(MyEntity test) throws OperationException {
try {
em.persist(test);
} catch (Exception e) {
logger.error("ERROR saving test", e);
throw new OperationException("PS-SERVER");
}
}
答案 0 :(得分:0)
本准则运作良好。
问题在于项目中的另一个@Repository
类正在进行
@Inject
private SessionFactory sessionFactory;
即使代码不会在测试服务中调用,也会占用连接。我还不确定它是如何工作的,但是一旦用替换代码
@PersistenceContext
private EntityManager em;
它有效。