要实现多数据源的动态添加数据源,实现DynamicDataSourcePropertiesCustomizer 接口即可修改数据源的配置
/**
* 配置动态数据源
*
* @author Stan
* @date 2022-07-10
*/
@Configuration
@Slf4j
public class DynamicDatasourceConfig implements DynamicDataSourcePropertiesCustomizer {
@Resource
private UrlResolver urlResolver;
@Override
public void customize(DynamicDataSourceProperties dynamicDataSourceProperties) {
Map<String, DataSourceProperty> datasource = dynamicDataSourceProperties.getDatasource();
//获取数据库所在的服务器
String serviceUrl = serviceResolver.resolve("score");
if (StringUtil.isNotBlank(serviceUrl)) {
try {
//获取服务器地址中的IP地址,既数据库的IP地址
URI uri = new URI(serviceUrl);
String host = uri.getHost();
//成绩数据库
if (!datasource.containsKey("score")) {
DataSourceProperty property = new DataSourceProperty();
property.setUrl("jdbc:mysql://" + host + ":3306/score?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8");
property.setUsername("admin");
property.setPassword("XXXXXX");
property.setDriverClassName("com.mysql.cj.jdbc.Driver");
datasource.put("score", property);
}
//成绩历史数据库
if (!datasource.containsKey("score_history")) {
DataSourceProperty property = new DataSourceProperty();
property.setUrl("jdbc:mysql://" + host + ":3306/score_his?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8");
property.setUsername("admin");
property.setPassword("XXXXXX");
property.setDriverClassName("com.mysql.cj.jdbc.Driver");
datasource.put("score_history", property);
}
} catch (URISyntaxException exception) {
log.error("服务器地址获取失败:地址错误:{}", serviceUrl, exception);
}
}
}
}