序
數(shù)據(jù)庫的相關(guān)配置理茎,一般來說是不會(huì)頻繁變的,特別是當(dāng)數(shù)據(jù)庫連接使用的是域名而不是ip地址的時(shí)候褂微,這樣即使ip地址變化了,也不影響業(yè)務(wù)系統(tǒng)园爷。這里呢宠蚂,我們講一下如果真的是迫不得已的時(shí)候,有沒有不重啟就可以更改配置的方法童社。
思路
有很多種方案求厕,這里我們講一下基于SpringCloud的RefreshScope的方案。
數(shù)據(jù)庫配置實(shí)例
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
public class DbConfig {
@Bean
@RefreshScope //refresh
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
}
更新
調(diào)用一下服務(wù)的refresh端點(diǎn)就可以了
curl -i -X POST http://localhost:9001/refresh
驗(yàn)證
@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();
}
}
}
這里跑一個(gè)定時(shí)任務(wù)扰楼,不停地調(diào)用數(shù)據(jù)查詢方法呀癣,然后中途改下密碼,然后refresh一下弦赖,看是否報(bào)錯(cuò)