springboot2动态数据源的绑定
由于springboot2更新了绑定参数的api,部分springboot1用于绑定的工具类如RelaxedPropertyResolver已经无法在新版本中使用。本文实现参考了https://blog.csdn.net/catoop/article/details/50575038这篇文章,大致思路是一致的,如果需要详细实现可以参考。都是通过AbstractRoutingDataSource实现动态数据源的切换,以前我用spring配置多数据源的时候就是通过它实现的,有兴趣的可以了解下其原理,这里就不多赘述了。
废话不多说了,先上数据源注册工具类,springboot2与1的主要区别也就在这:
MultiDataSourceRegister.java:
package top.ivan.demo.springboot.mapper;import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.context.properties.source.ConfigurationPropertyNameAliases;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class MultiDataSourceRegister implements EnvironmentAware, ImportBeanDefinitionRegistrar {
</span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">final</span> <span style="color: #0000ff;">static</span> ConfigurationPropertyNameAliases aliases = <span style="color: #0000ff;">new</span> ConfigurationPropertyNameAliases(); <span style="color: #008000;">//</span><span style="color: #008000;">别名</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> { </span><span style="color: #008000;">//</span><span style="color: #008000;">由于部分数据源配置不同,所以在此处添加别名,避免切换数据源出现某些参数无法注入的情况</span> aliases.addAliases("url", <span style="color: #0000ff;">new</span> String[]{"jdbc-url"<span style="color: #000000;">}); aliases.addAliases(</span>"username", <span style="color: #0000ff;">new</span> String[]{"user"<span style="color: #000000;">}); } </span><span style="color: #0000ff;">private</span> Environment evn; <span style="color: #008000;">//</span><span style="color: #008000;">配置上下文(也可以理解为配置文件的获取工具)</span> <span style="color: #0000ff;">private</span> Map<String, DataSource> sourceMap; <span style="color: #008000;">//</span><span style="color: #008000;">数据源列表</span> <span style="color: #0000ff;">private</span> Binder binder; <span style="color: #008000;">//</span><span style="color: #008000;">参数绑定工具</span> <span style="color: #008000;">/**</span><span style="color: #008000;"> * ImportBeanDefinitionRegistrar接口的实现方法,通过该方法可以按照自己的方式注册bean * * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> annotationMetadata * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> beanDefinitionRegistry </span><span style="color: #008000;">*/</span><span style="color: #000000;"> @Override </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { Map config, properties, defaultConfig </span>= binder.bind("spring.datasource", Map.<span style="color: #0000ff;">class</span>).get(); <span style="color: #008000;">//</span><span style="color: #008000;">获取所有数据源配置</span> sourceMap = <span style="color: #0000ff;">new</span> HashMap<>(); <span style="color: #008000;">//</span><span style="color: #008000;">默认配置</span> properties =<span style="color: #000000;"> defaultConfig; String typeStr </span>= evn.getProperty("spring.datasource.type"); <span style="color: #008000;">//</span><span style="color: #008000;">默认数据源类型</span> Class<? <span style="color: #0000ff;">extends</span> DataSource> clazz = getDataSourceType(typeStr); <span style="color: #008000;">//</span><span style="color: #008000;">获取数据源类型</span> DataSource consumerDatasource, defaultDatasource = bind(clazz, properties); <span style="color: #008000;">//</span><span style="color: #008000;">绑定默认数据源参数</span> List<Map> configs = binder.bind("spring.datasource.multi", Bindable.listOf(Map.<span style="color: #0000ff;">class</span>)).get(); <span style="color: #008000;">//</span><span style="color: #008000;">获取其他数据源配置</span> <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">int</span> i = 0; i < configs.size(); i++) { <span style="color: #008000;">//</span><span style="color: #008000;">遍历生成其他数据源</span> config =<span style="color: #000000;"> configs.get(i); clazz </span>= getDataSourceType((String) config.get("type"<span style="color: #000000;">)); </span><span style="color: #0000ff;">if</span> ((<span style="color: #0000ff;">boolean</span>) config.getOrDefault("extend", Boolean.TRUE)) { <span style="color: #008000;">//</span><span style="color: #008000;">获取extend字段,未定义或为true则为继承状态</span> properties = <span style="color: #0000ff;">new</span> HashMap(defaultConfig); <span style="color: #008000;">//</span><span style="color: #008000;">继承默认数据源配置</span> properties.putAll(config); <span style="color: #008000;">//</span><span style="color: #008000;">添加数据源参数</span> } <span style="color: #0000ff;">else</span><span style="color: #000000;"> { properties </span>= config; <span style="color: #008000;">//</span><span style="color: #008000;">不继承默认配置</span>
}
consumerDatasource = bind(clazz, properties); //绑定参数
sourceMap.put(config.get("key").toString(), consumerDatasource); //获取数据源的key,以便通过该key可以定位到数据源
}
GenericBeanDefinition define = new GenericBeanDefinition(); //bean定义类
define.setBeanClass(MultiDataSource.class); //设置bean的类型,此处MultiDataSource是继承AbstractRoutingDataSource的实现类
MutablePropertyValues mpv = define.getPropertyValues(); //需要注入的参数,类似spring配置文件中的<property/>
mpv.add("defaultTargetDataSource", defaultDatasource); //添加默认数据源,避免key不存在的情况没有数据源可用
mpv.add("targetDataSources", sourceMap); //添加其他数据源
beanDefinitionRegistry.registerBeanDefinition("datasource", define); //将该bean注册为datasource,不使用springboot自动生成的datasource
}</span><span style="color: #008000;">/**</span><span style="color: #008000;"> * 通过字符串获取数据源class对象 * * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> typeStr * </span><span style="color: #808080;">@return</span> <span style="color: #008000;">*/</span> <span style="color: #0000ff;">private</span> Class<? <span style="color: #0000ff;">extends</span> DataSource><span style="color: #000000;"> getDataSourceType(String typeStr) { Class</span><? <span style="color: #0000ff;">extends</span> DataSource><span style="color: #000000;"> type; </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> { </span><span style="color: #0000ff;">if</span> (StringUtils.hasLength(typeStr)) { <span style="color: #008000;">//</span><span style="color: #008000;">字符串不为空则通过反射获取class对象</span> type = (Class<? <span style="color: #0000ff;">extends</span> DataSource><span style="color: #000000;">) Class.forName(typeStr); } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> { type </span>= HikariDataSource.<span style="color: #0000ff;">class</span>; <span style="color: #008000;">//</span><span style="color: #008000;">默认为hikariCP数据源,与springboot默认数据源保持一致</span>
}
return type;
} catch (Exception e) {
throw new IllegalArgumentException("can not resolve class with type: " + typeStr); //无法通过反射获取class对象的情况则抛出异常,该情况一般是写错了,所以此次抛出一个runtimeexception
}
}</span><span style="color: #008000;">/**</span><span style="color: #008000;"> * 绑定参数,以下三个方法都是参考DataSourceBuilder的bind方法实现的,目的是尽量保证我们自己添加的数据源构造过程与springboot保持一致 * * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> result * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> properties </span><span style="color: #008000;">*/</span> <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> bind(DataSource result, Map properties) { ConfigurationPropertySource source </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> MapConfigurationPropertySource(properties); Binder binder </span>= <span style="color: #0000ff;">new</span> Binder(<span style="color: #0000ff;">new</span><span style="color: #000000;"> ConfigurationPropertySource[]{source.withAliases(aliases)}); binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result)); </span><span style="color: #008000;">//</span><span style="color: #008000;">将参数绑定到对象</span>
}
</span><span style="color: #0000ff;">private</span> <T <span style="color: #0000ff;">extends</span> DataSource> T bind(Class<T><span style="color: #000000;"> clazz, Map properties) { ConfigurationPropertySource source </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> MapConfigurationPropertySource(properties); Binder binder </span>= <span style="color: #0000ff;">new</span> Binder(<span style="color: #0000ff;">new</span><span style="color: #000000;"> ConfigurationPropertySource[]{source.withAliases(aliases)}); </span><span style="color: #0000ff;">return</span> binder.bind(ConfigurationPropertyName.EMPTY, Bindable.of(clazz)).get(); <span style="color: #008000;">//</span><span style="color: #008000;">通过类型绑定参数并获得实例对象</span>
}
</span><span style="color: #008000;">/**</span><span style="color: #008000;"> * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> clazz * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> sourcePath 参数路径,对应配置文件中的值,如: spring.datasource * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> <T> * </span><span style="color: #808080;">@return</span> <span style="color: #008000;">*/</span> <span style="color: #0000ff;">private</span> <T <span style="color: #0000ff;">extends</span> DataSource> T bind(Class<T><span style="color: #000000;"> clazz, String sourcePath) { Map properties </span>= binder.bind(sourcePath, Map.<span style="color: #0000ff;">class</span><span style="color: #000000;">).get(); </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> bind(clazz, properties); } </span><span style="color: #008000;">/**</span><span style="color: #008000;"> * EnvironmentAware接口的实现方法,通过aware的方式注入,此处是environment对象 * * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> environment </span><span style="color: #008000;">*/</span><span style="color: #000000;"> @Override </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> setEnvironment(Environment environment) { </span><span style="color: #0000ff;">this</span>.evn =<span style="color: #000000;"> environment; binder </span>= Binder.get(evn); <span style="color: #008000;">//</span><span style="color: #008000;">绑定配置器</span>
}
}
此处放出我的配置文件application.yml :
spring: datasource: password: 123456 url: jdbc:mysql://127.0.0.1:3306/graduation_project?useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: ivan openMulti: true type: com.zaxxer.hikari.HikariDataSource idle-timeout: 30000 multi: - key: default1 password: 123456 url: jdbc:mysql://127.0.0.1:3306/graduation_project?useUnicode=true&characterEncoding=UTF-8 idle-timeout: 20000 driver-class-name: com.mysql.jdbc.Driver username: ivan type: com.alibaba.druid.pool.DruidDataSource - key: gd password: 123456 url: jdbc:mysql://gd.badtheway.xin:****/graduation_project?useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: ivan mybatis: config-location: classpath:mapper/configure.xml mapper-locations: classpath:mapper/*Mapper.xml
这边说明一下,spring.datasource路径下的配置即默认数据源的配置,我是为了个人美感以及方便,所以在配置多数据源时使用spring.datasource.multi这个路径,假如需要更改的话修改MultiDataSourceRegister.java里面相应的值就可以了。
最后别忘了在@SpringBootApplication加上@Import(MultiDataSourceRegister.class)
下面是我自己使用的一些切面配置,通过@MultiDataSource$DataSource注解标记需要切换数据源的类,可以通过方法体参数->方法注解->类注解实现切换数据源。供大家参考:
MultiDataSource.java:
package top.ivan.demo.springboot.mapper;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;
import java.util.Set;public class MultiDataSource extends AbstractRoutingDataSource {
</span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">final</span> <span style="color: #0000ff;">static</span> ThreadLocal<String> DATA_SOURCE_KEY = <span style="color: #0000ff;">new</span> ThreadLocal<>(); <span style="color: #008000;">//</span><span style="color: #008000;">保存当前线程的数据源对应的key</span> <span style="color: #0000ff;">private</span> Set<Object> keySet; <span style="color: #008000;">//</span><span style="color: #008000;">所有数据源的key集合</span> <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> switchSource(String key) { DATA_SOURCE_KEY.set(key); </span><span style="color: #008000;">//</span><span style="color: #008000;">切换当先线程的key</span>
}
</span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> clear() { DATA_SOURCE_KEY.remove(); </span><span style="color: #008000;">//</span><span style="color: #008000;">移除key值</span>
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> Object execute(String ds, Run run) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> Throwable { switchSource(ds); </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> { </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> run.run(); } </span><span style="color: #0000ff;">finally</span><span style="color: #000000;"> { clear(); } } </span><span style="color: #008000;">//</span><span style="color: #008000;">AbstractRoutingDataSource抽象类实现方法,即获取当前线程数据源的key</span>
@Override
protected Object determineCurrentLookupKey() {
String key = DATA_SOURCE_KEY.get();
if (!keySet.contains(key)) {
logger.info(String.format("can not found datasource by key: '%s',this session may use default datasource", key));
}
return key;
}</span><span style="color: #008000;">/**</span><span style="color: #008000;"> * 在获取key的集合,目的只是为了添加一些告警日志 </span><span style="color: #008000;">*/</span><span style="color: #000000;"> @Override </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> afterPropertiesSet() { </span><span style="color: #0000ff;">super</span><span style="color: #000000;">.afterPropertiesSet(); </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> { Field sourceMapField </span>= AbstractRoutingDataSource.<span style="color: #0000ff;">class</span>.getDeclaredField("resolvedDataSources"<span style="color: #000000;">); sourceMapField.setAccessible(</span><span style="color: #0000ff;">true</span><span style="color: #000000;">); Map</span><Object, javax.sql.DataSource> sourceMap = (Map<Object, javax.sql.DataSource>) sourceMapField.get(<span style="color: #0000ff;">this</span><span style="color: #000000;">); </span><span style="color: #0000ff;">this</span>.keySet =<span style="color: #000000;"> sourceMap.keySet(); sourceMapField.setAccessible(</span><span style="color: #0000ff;">false</span><span style="color: #000000;">); } </span><span style="color: #0000ff;">catch</span> (NoSuchFieldException |<span style="color: #000000;"> IllegalAccessException e) { e.printStackTrace(); } } </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">interface</span><span style="color: #000000;"> Run { Object run() </span><span style="color: #0000ff;">throws</span><span style="color: #000000;"> Throwable; } </span><span style="color: #008000;">/**</span><span style="color: #008000;"> * 用于获取AOP切点及数据源key的注解 </span><span style="color: #008000;">*/</span><span style="color: #000000;"> @Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented </span><span style="color: #0000ff;">public</span> @<span style="color: #0000ff;">interface</span><span style="color: #000000;"> DataSource { String value() </span><span style="color: #0000ff;">default</span> ""; <span style="color: #008000;">//</span><span style="color: #008000;">该值即key值</span>
}
</span><span style="color: #008000;">/**</span><span style="color: #008000;"> * 声明切面 </span><span style="color: #008000;">*/</span><span style="color: #000000;"> @Component @Aspect @Order(</span>-10) <span style="color: #008000;">//</span><span style="color: #008000;">使该切面在事务之前执行</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> DataSourceSwitchInterceptor { </span><span style="color: #008000;">/**</span><span style="color: #008000;"> * 扫描所有含有@MultiDataSource$DataSource注解的类 </span><span style="color: #008000;">*/</span><span style="color: #000000;"> @Pointcut(</span>"@within(top.ivan.demo.springboot.mapper.MultiDataSource.DataSource)"<span style="color: #000000;">) </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> switchDataSource() { } </span><span style="color: #008000;">/**</span><span style="color: #008000;"> * 使用around方式监控 * </span><span style="color: #808080;">@param</span><span style="color: #008000;"> point * </span><span style="color: #808080;">@return</span><span style="color: #008000;"> * </span><span style="color: #808080;">@throws</span><span style="color: #008000;"> Throwable </span><span style="color: #008000;">*/</span><span style="color: #000000;"> @Around(</span>"switchDataSource()"<span style="color: #000000;">) </span><span style="color: #0000ff;">public</span> Object switchByMethod(ProceedingJoinPoint point) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> Throwable { Method method </span>= getMethodByPoint(point); <span style="color: #008000;">//</span><span style="color: #008000;">获取执行方法</span> Parameter[] params = method.getParameters(); <span style="color: #008000;">//</span><span style="color: #008000;">获取执行参数</span>
Parameter parameter;
String source = null;
boolean isDynamic = false;
for (int i = params.length - 1; i >= 0; i--) { //扫描是否有参数带有@DataSource注解
parameter = params[i];
if (parameter.getAnnotation(DataSource.class) != null && point.getArgs()[i] instanceof String) {
source = (String) point.getArgs()[i]; //key值即该参数的值,要求该参数必须为String类型
isDynamic = true;
break;
}
}
if (!isDynamic) { //不存在参数带有Datasource注解
DataSource dataSource = method.getAnnotation(DataSource.class); //获取方法的@DataSource注解
if (null == dataSource || !StringUtils.hasLength(dataSource.value())) { //方法不含有注解
dataSource = method.getDeclaringClass().getAnnotation(DataSource.class); //获取类级别的@DataSource注解
}
if (null != dataSource) {
source = dataSource.value(); //设置key值
}
}
return persistBySource(source, point); //继续执行该方法
}</span><span style="color: #0000ff;">private</span> Object persistBySource(String source, ProceedingJoinPoint point) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> Throwable { </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> { switchSource(source); </span><span style="color: #008000;">//</span><span style="color: #008000;">切换数据源</span> <span style="color: #0000ff;">return</span> point.proceed(); <span style="color: #008000;">//</span><span style="color: #008000;">执行</span> } <span style="color: #0000ff;">finally</span><span style="color: #000000;"> { clear(); </span><span style="color: #008000;">//</span><span style="color: #008000;">清空key值</span>
}
}</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> Method getMethodByPoint(ProceedingJoinPoint point) { MethodSignature methodSignature </span>=<span style="color: #000000;"> (MethodSignature) point.getSignature(); </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> methodSignature.getMethod(); } }
}
示例:
package top.ivan.demo.springboot.mapper;import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import top.ivan.demo.springboot.pojo.ProductPreview;import java.util.List;
@Mapper
@MultiDataSource.DataSource("ds1")
public interface PreviewMapper {</span><span style="color: #008000;">//</span><span style="color: #008000;">使用ds的值作为key</span> List<ProductPreview> getList(@Param("start") <span style="color: #0000ff;">int</span> start, @Param("count") <span style="color: #0000ff;">int</span><span style="color: #000000;"> count, @MultiDataSource.DataSource String ds); </span><span style="color: #008000;">//</span><span style="color: #008000;">使用“ds2”作为key</span> @MultiDataSource.DataSource("ds2"<span style="color: #000000;">) List</span><ProductPreview> getList2(@Param("start") <span style="color: #0000ff;">int</span> start, @Param("count") <span style="color: #0000ff;">int</span><span style="color: #000000;"> count); </span><span style="color: #008000;">//</span><span style="color: #008000;">使用“ds1”作为key</span> List<ProductPreview> getList3(@Param("start") <span style="color: #0000ff;">int</span> start, @Param("count") <span style="color: #0000ff;">int</span><span style="color: #000000;"> count);
}
这几天刚接触springboot,还处于小白的状态,假如有什么问题的话欢迎大家指教
------------------------------------------------------------------------------------------------------------------------------
附上源码文件: https://files.cnblogs.com/files/badtheway/springboot.zip
原文地址:https://www.cnblogs.com/badtheway/p/9061065.html