Programing

Spring Boot JPA-자동 재 연결 구성

crosscheck 2020. 8. 18. 07:13
반응형

Spring Boot JPA-자동 재 연결 구성


좋은 작은 Spring Boot JPA 웹 애플리케이션이 있습니다. Amazon Beanstalk에 배포되며 데이터 유지를 위해 Amazon RDS를 사용합니다. 그러나 자주 사용되지 않으므로 이러한 종류의 예외로 잠시 후 실패합니다.

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : 서버에서 성공적으로 수신 한 마지막 패킷은 79,870,633 밀리 초 전이었습니다.
서버로 성공적으로 전송 된 마지막 패킷은 79,870,634 밀리 초 전이었습니다. 서버 구성 값 'wait_timeout'보다 깁니다. 이 문제를 방지하려면 응용 프로그램에서 사용하기 전에 연결 유효성 만료 및 / 또는 테스트, 클라이언트 시간 초과에 대한 서버 구성 값 늘리기 또는 커넥터 / J 연결 속성 'autoReconnect = true'사용을 고려해야합니다.

이 설정을 구성하는 방법을 잘 모르겠고 http://spring.io (아주 좋은 사이트) 에서 정보를 찾을 수 없습니다 . 정보에 대한 아이디어 나 지침은 무엇입니까?


나는 부팅이 DataSource당신을 위해 구성한다고 가정 합니다. 이 경우 MySQL을 사용하고 있으므로 application.properties최대 1.3에 다음을 추가 할 수 있습니다.

spring.datasource.testOnBorrow=true
spring.datasource.validationQuery=SELECT 1

djxak이 주석에 언급 한 바와 같이, 네 개의 연결 풀 봄 부트 지원을위한 1.4을 정의의 특정 네임 스페이스는 : tomcat, hikari, dbcp, dbcp2( dbcp1.5으로 사용되지 않습니다). 사용중인 연결 풀을 확인하고 해당 기능이 지원되는지 확인해야합니다. 위의 예는 바람둥이 용이므로 1.4+에서 다음과 같이 작성해야합니다.

spring.datasource.tomcat.testOnBorrow=true 
spring.datasource.tomcat.validationQuery=SELECT 1

의 사용이 있습니다 autoReconnect됩니다 하지 않는 것이 좋습니다 :

이 기능의 사용은 응용 프로그램이 SQLException을 제대로 처리하지 못할 때 세션 상태 및 데이터 일관성과 관련된 부작용이 있고 다음으로 인한 SQLException을 처리하도록 응용 프로그램을 구성 할 수없는 경우에만 사용하도록 설계 되었기 때문에 권장되지 않습니다. 제대로 작동하지 않고 부실한 연결.


위의 제안은 저에게 효과적이지 않았습니다. 실제로 효과가 있었던 것은 application.properties에 다음 줄을 포함하는 것입니다.

spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 3600000
spring.datasource.validationQuery = SELECT 1

여기 에서 설명을 찾을 수 있습니다.


방금 Spring Boot 1.4로 이동했으며 이러한 속성의 이름이 변경되었음을 알았습니다.

spring.datasource.dbcp.test-while-idle=true
spring.datasource.dbcp.time-between-eviction-runs-millis=3600000
spring.datasource.dbcp.validation-query=SELECT 1

spring.datasource.tomcat.testOnBorrow=trueapplication.properties의 설정 이 작동하지 않았습니다.

아래와 같이 프로그래밍 방식으로 설정하면 문제없이 작동했습니다.

import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;    

@Bean
public DataSource dataSource() {
    PoolProperties poolProperties = new PoolProperties();
    poolProperties.setUrl(this.properties.getDatabase().getUrl());         
    poolProperties.setUsername(this.properties.getDatabase().getUsername());            
    poolProperties.setPassword(this.properties.getDatabase().getPassword());

    //here it is
    poolProperties.setTestOnBorrow(true);
    poolProperties.setValidationQuery("SELECT 1");

    return new DataSource(poolProperties);
}

비슷한 문제가 있습니다. Spring 4 및 Tomcat 8. Spring 구성으로 문제를 해결합니다.

<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
    <property name="initialSize" value="10" />
    <property name="maxActive" value="25" />
    <property name="maxIdle" value="20" />
    <property name="minIdle" value="10" />
     ...
    <property name="testOnBorrow" value="true" />
    <property name="validationQuery" value="SELECT 1" />
 </bean>

I have tested. It works well! This two line does everything in order to reconnect to database:

<property name="testOnBorrow" value="true" />
<property name="validationQuery" value="SELECT 1" />

whoami's answer is the correct one. Using the properties as suggested I was unable to get this to work (using Spring Boot 1.5.3.RELEASE)

I'm adding my answer since it's a complete configuration class so it might help someone using Spring Boot:

@Configuration
@Log4j
public class SwatDataBaseConfig {

    @Value("${swat.decrypt.location}")
    private String fileLocation;

    @Value("${swat.datasource.url}")
    private String dbURL;

    @Value("${swat.datasource.driver-class-name}")
    private String driverName;

    @Value("${swat.datasource.username}")
    private String userName;

    @Value("${swat.datasource.password}")
    private String hashedPassword;

    @Bean
    public DataSource primaryDataSource() {
        PoolProperties poolProperties = new PoolProperties();
        poolProperties.setUrl(dbURL);
        poolProperties.setUsername(userName);
        poolProperties.setPassword(password);
        poolProperties.setDriverClassName(driverName);
        poolProperties.setTestOnBorrow(true);
        poolProperties.setValidationQuery("SELECT 1");
        poolProperties.setValidationInterval(0);
        DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
        return ds;
    }
}

In case anyone is using custom DataSource

@Bean(name = "managementDataSource")
@ConfigurationProperties(prefix = "management.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

Properties should look like the following. Notice the @ConfigurationProperties with prefix. The prefix is everything before the actual property name

management.datasource.test-on-borrow=true
management.datasource.validation-query=SELECT 1

A reference for Spring Version 1.4.4.RELEASE


As some people already pointed out, spring-boot 1.4+, has specific namespaces for the four connections pools. By default, hikaricp is used in spring-boot 2+. So you will have to specify the SQL here. The default is SELECT 1. Here's what you would need for DB2 for example: spring.datasource.hikari.connection-test-query=SELECT current date FROM sysibm.sysdummy1

Caveat: If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none

참고URL : https://stackoverflow.com/questions/22684807/spring-boot-jpa-configuring-auto-reconnect

반응형