@[TOC]
1 不停机通过接口切换数据源
@GetMapping("/updateDruidProperty")
@Anonymous
public AjaxResult updateProperty(){
DruidDataSource dataSource = SpringUtils.getBean("masterDataSource");
try {
Properties properties = new Properties();
// 这里是测试写法,具体的value可以通过请求参数传递过来
// 例如 http://localhost:8080/test?druid.url="...."&&druid.username="...."&&druid.password="...."
properties.setProperty("druid.url","jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8");
properties.setProperty("druid.username","root");
properties.setProperty("druid.password","root");
dataSource.restart(properties);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return AjaxResult.success();
}
2 随便写个接口测试
@GetMapping("/insertUser")
@Anonymous
public AjaxResult insertUser(){
SysUser user = new SysUser();
user.setUserName("胡云峰");
user.setNickName("logicfeng");
userService.insertUser(user);
String password = configurableEnvironment.getProperty("spring.datasource.druid.master.password");
return AjaxResult.success(password);
}
3 使用apifox测试
3.1 切换数据源前新增数据
- 发起请求
- 测试结果
3.2 切换数据源
- 发起请求
3.3 测试新的数据源新增用户
- 发起请求
- 测试结果