注:本文的多數(shù)據(jù)源配置及切換的實(shí)現(xiàn)方法是,在框架中封裝,具體項(xiàng)目中配置及使用,也適用于多模塊項(xiàng)目
配置文件數(shù)據(jù)源讀取
通過springboot的Envioment和Binder對(duì)象進(jìn)行讀取,無需手動(dòng)聲明DataSource的Bean
yml數(shù)據(jù)源配置格式如下:
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為主數(shù)據(jù)庫必須配置,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" )); } |
動(dòng)態(tài)加入數(shù)據(jù)源
定義獲取數(shù)據(jù)源的Service,具體項(xiàng)目中進(jìn)行實(shí)現(xiàn)
1
2
3
|
public interface ExtraDataSourceService { List<DataSourceModel> getExtraDataSourc(); } |
獲取對(duì)應(yīng)Service的所有實(shí)現(xiàn)類進(jìn)行調(diào)用
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; } |
通過代碼進(jìn)行數(shù)據(jù)源注冊(cè)
主要是用過繼承類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
|
// 創(chuàng)建數(shù)據(jù)源 public boolean createDataSource(String key, String driveClass, String url, String username, String password, String databasetype) { try { try { // 排除連接不上的錯(cuò)誤 Class.forName(driveClass); DriverManager.getConnection(url, username, password); // 相當(dāng)于連接數(shù)據(jù)庫 } 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 ); //初始化時(shí)建立物理連接的個(gè)數(shù)。初始化發(fā)生在顯示調(diào)用init方法,或者第一次getConnection時(shí) druidDataSource.setMaxActive( 20 ); //最大連接池?cái)?shù)量 druidDataSource.setMaxWait( 60000 ); //獲取連接時(shí)最大等待時(shí)間,單位毫秒。當(dāng)鏈接數(shù)已經(jīng)達(dá)到了最大鏈接數(shù)的時(shí)候,應(yīng)用如果還要獲取鏈接就會(huì)出現(xiàn)等待的現(xiàn)象,等待鏈接釋放并回到鏈接池,如果等待的時(shí)間過長(zhǎng)就應(yīng)該踢掉這個(gè)等待,不然應(yīng)用很可能出現(xiàn)雪崩現(xiàn)象 druidDataSource.setMinIdle( 5 ); //最小連接池?cái)?shù)量 String validationQuery = "select 1 from dual" ; druidDataSource.setTestOnBorrow( true ); //申請(qǐng)連接時(shí)執(zhí)行validationQuery檢測(cè)連接是否有效,這里建議配置為TRUE,防止取到的連接不可用 druidDataSource.setTestWhileIdle( true ); //建議配置為true,不影響性能,并且保證安全性。申請(qǐng)連接的時(shí)候檢測(cè),如果空閑時(shí)間大于timeBetweenEvictionRunsMillis,執(zhí)行validationQuery檢測(cè)連接是否有效。 druidDataSource.setValidationQuery(validationQuery); //用來檢測(cè)連接是否有效的sql,要求是一個(gè)查詢語句。如果validationQuery為null,testOnBorrow、testOnReturn、testWhileIdle都不會(huì)起作用。 druidDataSource.setFilters( "stat" ); //屬性類型是字符串,通過別名的方式配置擴(kuò)展插件,常用的插件有:監(jiān)控統(tǒng)計(jì)用的filter:stat日志用的filter:log4j防御sql注入的filter:wall druidDataSource.setTimeBetweenEvictionRunsMillis( 60000 ); //配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒 druidDataSource.setMinEvictableIdleTimeMillis( 180000 ); //配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒,這里配置為3分鐘180000 druidDataSource.setKeepAlive( true ); //打開druid.keepAlive之后,當(dāng)連接池空閑時(shí),池中的minIdle數(shù)量以內(nèi)的連接,空閑時(shí)間超過minEvictableIdleTimeMillis,則會(huì)執(zhí)行keepAlive操作,即執(zhí)行druid.validationQuery指定的查詢SQL,一般為select * from dual,只要minEvictableIdleTimeMillis設(shè)置的小于防火墻切斷連接時(shí)間,就可以保證當(dāng)連接空閑時(shí)自動(dòng)做保活檢測(cè),不會(huì)被防火墻切斷 druidDataSource.setRemoveAbandoned( true ); //是否移除泄露的連接/超過時(shí)間限制是否回收。 druidDataSource.setRemoveAbandonedTimeout( 3600 ); //泄露連接的定義時(shí)間(要超過最大事務(wù)的處理時(shí)間);單位為秒。這里配置為1小時(shí) druidDataSource.setLogAbandoned( true ); //移除泄露連接發(fā)生是是否記錄日志 druidDataSource.init(); this .dynamicTargetDataSources.put(key, druidDataSource); setTargetDataSources( this .dynamicTargetDataSources); // 將map賦值給父類的TargetDataSources super .afterPropertiesSet(); // 將TargetDataSources中的連接信息放入resolvedDataSources管理 log.info(key+ "數(shù)據(jù)源初始化成功" ); //log.info(key+"數(shù)據(jù)源的概況:"+druidDataSource.dump()); return true ; } catch (Exception e) { log.error(e + "" ); return false ; } } |
通過切面注解統(tǒng)一切換
定義注解
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 ); // 對(duì)當(dāng)前線程的操作-線程安全的 private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); // 調(diào)用此方法,切換數(shù)據(jù)源 public static void setDataSource(String dataSource) { contextHolder.set(dataSource); log.info( "已切換到數(shù)據(jù)源:{}" ,dataSource); } // 獲取數(shù)據(jù)源 public static String getDataSource() { return contextHolder.get(); } // 刪除數(shù)據(jù)源 public static void clearDataSource() { contextHolder.remove(); log.info( "已切換到主數(shù)據(jù)源" ); } } |
定義切面
方法的注解優(yōu)先級(jí)高于類注解,一般用于Service的實(shí)現(xiàn)類
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; /** * 切面點(diǎn) 指定注解 * */ @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(); } } } |
分庫切換
開發(fā)過程中某個(gè)庫的某個(gè)表做了拆分操作,相同的某一次數(shù)據(jù)庫操作可能對(duì)應(yīng)到不同的庫,需要對(duì)方法級(jí)別進(jìn)行精確攔截,可以定義一個(gè)業(yè)務(wù)層面的切面,規(guī)定每個(gè)方法必須第一個(gè)參數(shù)為dbName,根據(jù)具體業(yè)務(wù)找到對(duì)應(yīng)的庫傳參
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 ){ //獲取方法定義參數(shù) DefaultParameterNameDiscoverer discover = new DefaultParameterNameDiscoverer(); String[] parameterNames = discover.getParameterNames(method); //獲取傳入目標(biāo)方法的參數(shù) 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(); } } } |
到此這篇關(guān)于springboot多數(shù)據(jù)源配置及切換的示例代碼詳解的文章就介紹到這了,更多相關(guān)springboot多數(shù)據(jù)源配置 內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.cnblogs.com/yanpeng19940119/archive/2020/09/20/13702454.html