注:本文的多数据源配置及切换的实现方法是,在框架中封装,具体项目中配置及使用,也适用于多模块项目
配置文件数据源读取
通过springboot的Envioment和Binder对象进行读取,无需手动声明DataSource的Bean
yml数据源配置格式如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
spring:
datasource:
master:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql: //localhost:3306/main?
useUnicode= true &characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
username: root
password: 11111
cluster:
- key: db1
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql: //localhost:3306/haopanframetest_db1?
useUnicode= true &characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
username: root
password: 11111
- key: db2
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql: //localhost:3306/haopanframetest_db2?
useUnicode= true &characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
username: root
password: 11111
|
master为主数据库必须配置,cluster下的为从库,选择性配置
获取配置文件信息代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@Autowired
private Environment env;
@Autowired
private ApplicationContext applicationContext;
private Binder binder;
binder = Binder.get(env);
List<Map> configs = binder.bind( "spring.datasource.cluster" , Bindable.listOf(Map. class )).get();
for ( int i = 0 ; i < configs.size(); i++) {
config = configs.get(i);
String key = ConvertOp.convert2String(config.get( "key" ));
String type = ConvertOp.convert2String(config.get( "type" ));
String driverClassName = ConvertOp.convert2String(config.get( "driverClassName" ));
String url = ConvertOp.convert2String(config.get( "url" ));
String username = ConvertOp.convert2String(config.get( "username" ));
String password = ConvertOp.convert2String(config.get( "password" ));
}
|
动态加入数据源
定义获取数据源的Service,具体项目中进行实现
1
2
3
|
public interface ExtraDataSourceService {
List<DataSourceModel> getExtraDataSourc();
}
|
获取对应Service的所有实现类进行调用
1
2
3
4
5
6
7
8
9
10
|
private List<DataSourceModel> getExtraDataSource(){
List<DataSourceModel> dataSourceModelList = new ArrayList<>();
Map<String, ExtraDataSourceService> res =
applicationContext.getBeansOfType(ExtraDataSourceService. class );
for (Map.Entry en :res.entrySet()) {
ExtraDataSourceService service = (ExtraDataSourceService)en.getValue();
dataSourceModelList.addAll(service.getExtraDataSourc());
}
return dataSourceModelList;
}
|
通过代码进行数据源注册
主要是用过继承类AbstractRoutingDataSource,重写setTargetDataSources/setDefaultTargetDataSource方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
// 创建数据源
public boolean createDataSource(String key, String driveClass, String url, String username, String password, String databasetype) {
try {
try { // 排除连接不上的错误
Class.forName(driveClass);
DriverManager.getConnection(url, username, password); // 相当于连接数据库
} catch (Exception e) {
return false ;
}
@SuppressWarnings ( "resource" )
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setName(key);
druidDataSource.setDriverClassName(driveClass);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
druidDataSource.setInitialSize( 1 ); //初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
druidDataSource.setMaxActive( 20 ); //最大连接池数量
druidDataSource.setMaxWait( 60000 ); //获取连接时最大等待时间,单位毫秒。当链接数已经达到了最大链接数的时候,应用如果还要获取链接就会出现等待的现象,等待链接释放并回到链接池,如果等待的时间过长就应该踢掉这个等待,不然应用很可能出现雪崩现象
druidDataSource.setMinIdle( 5 ); //最小连接池数量
String validationQuery = "select 1 from dual" ;
druidDataSource.setTestOnBorrow( true ); //申请连接时执行validationQuery检测连接是否有效,这里建议配置为TRUE,防止取到的连接不可用
druidDataSource.setTestWhileIdle( true ); //建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
druidDataSource.setValidationQuery(validationQuery); //用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
druidDataSource.setFilters( "stat" ); //属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall
druidDataSource.setTimeBetweenEvictionRunsMillis( 60000 ); //配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
druidDataSource.setMinEvictableIdleTimeMillis( 180000 ); //配置一个连接在池中最小生存的时间,单位是毫秒,这里配置为3分钟180000
druidDataSource.setKeepAlive( true ); //打开druid.keepAlive之后,当连接池空闲时,池中的minIdle数量以内的连接,空闲时间超过minEvictableIdleTimeMillis,则会执行keepAlive操作,即执行druid.validationQuery指定的查询SQL,一般为select * from dual,只要minEvictableIdleTimeMillis设置的小于防火墙切断连接时间,就可以保证当连接空闲时自动做保活检测,不会被防火墙切断
druidDataSource.setRemoveAbandoned( true ); //是否移除泄露的连接/超过时间限制是否回收。
druidDataSource.setRemoveAbandonedTimeout( 3600 ); //泄露连接的定义时间(要超过最大事务的处理时间);单位为秒。这里配置为1小时
druidDataSource.setLogAbandoned( true ); //移除泄露连接发生是是否记录日志
druidDataSource.init();
this .dynamicTargetDataSources.put(key, druidDataSource);
setTargetDataSources( this .dynamicTargetDataSources); // 将map赋值给父类的TargetDataSources
super .afterPropertiesSet(); // 将TargetDataSources中的连接信息放入resolvedDataSources管理
log.info(key+ "数据源初始化成功" );
//log.info(key+"数据源的概况:"+druidDataSource.dump());
return true ;
} catch (Exception e) {
log.error(e + "" );
return false ;
}
}
|
通过切面注解统一切换
定义注解
1
2
3
4
5
6
|
@Retention (RetentionPolicy.RUNTIME)
@Target ({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
@Documented
public @interface TargetDataSource {
String value() default "master" ; //该值即key值
}
|
定义基于线程的切换类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class DBContextHolder {
private static Logger log = LoggerFactory.getLogger(DBContextHolder. class );
// 对当前线程的操作-线程安全的
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
// 调用此方法,切换数据源
public static void setDataSource(String dataSource) {
contextHolder.set(dataSource);
log.info( "已切换到数据源:{}" ,dataSource);
}
// 获取数据源
public static String getDataSource() {
return contextHolder.get();
}
// 删除数据源
public static void clearDataSource() {
contextHolder.remove();
log.info( "已切换到主数据源" );
}
}
|
定义切面
方法的注解优先级高于类注解,一般用于Service的实现类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
@Aspect
@Component
@Order (Ordered.HIGHEST_PRECEDENCE)
public class DruidDBAspect {
private static Logger logger = LoggerFactory.getLogger(DruidDBAspect. class );
@Autowired
private DynamicDataSource dynamicDataSource;
/**
* 切面点 指定注解
* */
@Pointcut ( "@annotation(com.haopan.frame.common.annotation.TargetDataSource) " +
"|| @within(com.haopan.frame.common.annotation.TargetDataSource)" )
public void dataSourcePointCut() {
}
/**
* 拦截方法指定为 dataSourcePointCut
* */
@Around ( "dataSourcePointCut()" )
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Class targetClass = point.getTarget().getClass();
Method method = signature.getMethod();
TargetDataSource targetDataSource = (TargetDataSource)targetClass.getAnnotation(TargetDataSource. class );
TargetDataSource methodDataSource = method.getAnnotation(TargetDataSource. class );
if (targetDataSource != null || methodDataSource != null ){
String value;
if (methodDataSource != null ){
value = methodDataSource.value();
} else {
value = targetDataSource.value();
}
DBContextHolder.setDataSource(value);
logger.info( "DB切换成功,切换至{}" ,value);
}
try {
return point.proceed();
} finally {
logger.info( "清除DB切换" );
DBContextHolder.clearDataSource();
}
}
}
|
分库切换
开发过程中某个库的某个表做了拆分操作,相同的某一次数据库操作可能对应到不同的库,需要对方法级别进行精确拦截,可以定义一个业务层面的切面,规定每个方法必须第一个参数为dbName,根据具体业务找到对应的库传参
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
@Around ( "dataSourcePointCut()" )
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Class targetClass = point.getTarget().getClass();
Method method = signature.getMethod();
ProjectDataSource targetDataSource =
(ProjectDataSource)targetClass.getAnnotation(ProjectDataSource. class );
ProjectDataSource methodDataSource = method.getAnnotation(ProjectDataSource. class );
String value = "" ;
if (targetDataSource != null || methodDataSource != null ){
//获取方法定义参数
DefaultParameterNameDiscoverer discover = new DefaultParameterNameDiscoverer();
String[] parameterNames = discover.getParameterNames(method);
//获取传入目标方法的参数
Object[] args = point.getArgs();
for ( int i= 0 ;i<parameterNames.length;i++){
String pName = parameterNames[i];
if (pName.toLowerCase().equals( "dbname" )){
value = ConvertOp.convert2String(args[i]);
}
}
if (!StringUtil.isEmpty(value)){
DBContextHolder.setDataSource(value);
logger.info( "DB切换成功,切换至{}" ,value);
}
}
try {
return point.proceed();
} finally {
if (!StringUtil.isEmpty(value)){
logger.info( "清除DB切换" );
DBContextHolder.clearDataSource();
}
}
}
|
到此这篇关于springboot多数据源配置及切换的示例代码详解的文章就介绍到这了,更多相关springboot多数据源配置 内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/yanpeng19940119/archive/2020/09/20/13702454.html