上篇博客手动的一个个手动注入数据源,更好的做法是根据配置文件循环初始化所有数据源,最后注入动态数据源
1)配置文件 application.yml
spring:
application:
name: test
datasource:
driverClassName: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: xxxxx #默认数据源
username: root
password: root
names: first,second
first: #其他数据源
driverClassName: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url:xxxxx
username: root
password: root
second: #其他数据源
driverClassName: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://121.40.182.123:3306/gulimall_oms?useUnicode=true&characterEncoding=UTF-8
username: root
password: root
mybatis:
mapper-locations: classpath:mapper/*.xml
2)配置文件注入数据源
/**
* @author IT006651 * @date 2022/5/7 9:23 * @description: 注册动态数据源
*/
@Slf4j
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
//默认数据源(主数据源)
private DataSource defaultDataSource;
//其他数据源
private Map<String, DataSource> customDataSources = new HashMap<>();
/*凡注册到Spring容器内的bean,实现了EnvironmentAware接口重写setEnvironment方法后,在工程启动时可以获得application.properties的配置文件配置的属性值 */
@Override
public void setEnvironment(Environment environment) {
initDefaultDataSource(environment);
initCustomDataSources(environment);
}
/**
* * 向Spring容器中注入动态数据源
* *
* * @param importingClassMetadata
* * @param registry
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
// 将主数据源添加到更多数据源中
targetDataSources.put("dataSource", defaultDataSource);
DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
// 添加更多数据源
targetDataSources.putAll(customDataSources);
for (String key : customDataSources.keySet()) {
DynamicDataSourceContextHolder.dataSourceIds.add(key);
}
// 创建DynamicDataSource
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(DynamicDataSource.class);
beanDefinition.setSynthetic(true);
MutablePropertyValues mpv = beanDefinition.getPropertyValues();
mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
mpv.addPropertyValue("targetDataSources", targetDataSources);
registry.registerBeanDefinition("dataSource", beanDefinition);
}
private void initDefaultDataSource(Environment env) {
// 读取主数据源配置
Map<String, Object> dsMap = new HashMap<>();
dsMap.put("type", env.getProperty("spring.datasource.type"));
dsMap.put("driver-class-name", env.getProperty("spring.datasource.driver-class-name"));
dsMap.put("url", env.getProperty("spring.datasource.url"));
dsMap.put("username", env.getProperty("spring.datasource.username"));
dsMap.put("password", env.getProperty("spring.datasource.password"));
defaultDataSource = buildDataSource(dsMap);
dataBinder(defaultDataSource, env);
}
/**
* 利用读取的配置创建数据源 *
*
* @param dsMap
* @return
*/
public DataSource buildDataSource(Map<String, Object> dsMap) {
Object type = dsMap.get("type");
Class<? extends DataSource> dataSourceType;
try {
dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);
String driverClassName = dsMap.get("driver-class-name").toString();
String url = dsMap.get("url").toString();
String username = dsMap.get("username").toString();
String password = dsMap.get("password").toString();
DataSource defaultDataSource = DataSourceBuilder.create().type(dataSourceType).driverClassName(driverClassName).url(url).username(username).password(password).build();
return defaultDataSource;
} catch (ClassNotFoundException e) {
log.error("buildDataSource from config error!", e);
}
return null;
}
/**
* 为数据源绑定更多属性
*
* @param dataSource *
* @param env todo
*/
private void dataBinder(DataSource dataSource, Environment env) {
}
/**
* 初始化更多数据源
*/
private void initCustomDataSources(Environment env) {
// 读取配置文件获取更多数据源,也可以通过defaultDataSource读取数据库获取更多数据源
String dataSourceNames = env.getProperty("spring.datasource.names");
if (StringUtils.isNotBlank(dataSourceNames)) {
for (String dsPrefix : dataSourceNames.split(",")) {// 多个数据源
Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(env);
Binder binder = new Binder(sources);
BindResult<Properties> bindResult = binder.bind("spring.datasource." + dsPrefix, Properties.class);
Properties properties = bindResult.get();
Map<String, Object> dsMap = new HashMap<>();
dsMap.put("type", properties.getProperty("type"));
dsMap.put("driver-class-name", properties.getProperty("driverClassName"));
dsMap.put("url", properties.getProperty("url"));
dsMap.put("username", properties.getProperty("username"));
dsMap.put("password", properties.getProperty("password"));
DataSource ds = buildDataSource(dsMap);
dataBinder(ds, env);
customDataSources.put(dsPrefix, ds);
}
}
}
}
3) DynamicDataSourceContextHolder 类,决定当前数据库操作使用的数据源
public class DynamicDataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static List<String> dataSourceIds = new ArrayList<>();
public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getDataSourceType() {
return contextHolder.get();
}
public static void clearDataSourceType() {
contextHolder.remove();
}
/**
* 判断指定DataSrouce当前是否存在 *
*/
public static boolean containsDataSource(String dataSourceId) {
return dataSourceIds.contains(dataSourceId);
}
}
4)动态数据源类 DynamicDataSource
/**
* 动态数据库 * 重写determineCurrentLookupKey方法,决定当前使用的数据源是哪一个
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}
5)注解 +切面,加在service方法上,决定当前使用的数据源是哪一个
/**
* 在方法上使用,用于指定使用哪个数据源 *
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String name();
}
@Slf4j
@Aspect
@Component
public class DataSourceAspect implements Ordered {
@Pointcut("@annotation(com.hc.datasource.TargetDataSource)")
public void dataSourcePointCut() {
}
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
TargetDataSource ds = method.getAnnotation(TargetDataSource.class);
if (ds != null) {
DynamicDataSourceContextHolder.setDataSourceType(ds.name());
log.info("set datasource is " + ds.name());
}
try {
return point.proceed();
} finally {
DynamicDataSourceContextHolder.clearDataSourceType();
log.debug("clean datasource");
}
}
@Override
public int getOrder() {
return 1;
}
}
6)测试 确实动态切换数据源