Order
The relevant configuration of the database will not change frequently in general, especially when the database connection uses domain name instead of ip address, so that even if the ip address changes, the business system will not be affected. Here, let’s talk about whether there is a way to change the configuration without restarting if it is really necessary.
Train of thought
There are many schemes, so let’s talk about the RefreshScope scheme based on SpringCloud.
Database configuration instance
spring:
datasource:
platform: postgres
url: jdbc:postgresql://192.168.99.100:5432/postgres
driverClassName: org.postgresql.Driver
username: postgres
password: 123456
validation-query: SELECT 1
test-while-idle: true
test-on-borrow: true
Java configuration
@Configuration
public class DbConfig {
@Bean
@RefreshScope //refresh
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
}
Update
Just call the refresh endpoint of the service
curl -i -X POST http://localhost:9001/refresh
Verification
@Component
public class ScheduleTask {
@Autowired
UserRepository userRepository;
@Scheduled(fixedDelay = 5*1000 /**ms**/,initialDelay = 5*1000)
public void testDataSourceConn() {
try{
System.out.println("call jdbc");
userRepository.findAll();
}catch (Exception e){
e.printStackTrace();
}
}
}
Here we run a timed task, constantly calling the data query method, then changing the password in the middle, and then refresh to see if there is an error.