這篇文章給大家介紹springboot中怎么配置多數(shù)據(jù)源,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
我們擁有十年網(wǎng)頁設(shè)計(jì)和網(wǎng)站建設(shè)經(jīng)驗(yàn),從網(wǎng)站策劃到網(wǎng)站制作,我們的網(wǎng)頁設(shè)計(jì)師為您提供的解決方案。為企業(yè)提供網(wǎng)站設(shè)計(jì)制作、網(wǎng)站設(shè)計(jì)、微信開發(fā)、成都微信小程序、手機(jī)網(wǎng)站開發(fā)、H5高端網(wǎng)站建設(shè)、等業(yè)務(wù)。無論您有什么樣的網(wǎng)站設(shè)計(jì)或者設(shè)計(jì)方案要求,我們都將富于創(chuàng)造性的提供專業(yè)設(shè)計(jì)服務(wù)并滿足您的需求。
配置文件數(shù)據(jù)源讀取
通過springboot的Envioment和Binder對(duì)象進(jìn)行讀取,無需手動(dòng)聲明DataSource的Bean
yml數(shù)據(jù)源配置格式如下:
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下的為從庫,選擇性配置
獲取配置文件信息代碼如下
@Autowiredprivate Environment env;@Autowiredprivate ApplicationContext applicationContext;private Binder binder; binder = Binder.get(env); List
定義獲取數(shù)據(jù)源的Service,具體項(xiàng)目中進(jìn)行實(shí)現(xiàn)
public interface ExtraDataSourceService {ListgetExtraDataSourc(); }
獲取對(duì)應(yīng)Service的所有實(shí)現(xiàn)類進(jìn)行調(diào)用
private ListgetExtraDataSource(){ List dataSourceModelList = new ArrayList<>(); Map 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方法
// 創(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í)間過長就應(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檢測連接是否有效,這里建議配置為TRUE,防止取到的連接不可用druidDataSource.setTestWhileIdle(true);//建議配置為true,不影響性能,并且保證安全性。申請(qǐng)連接的時(shí)候檢測,如果空閑時(shí)間大于timeBetweenEvictionRunsMillis,執(zhí)行validationQuery檢測連接是否有效。druidDataSource.setValidationQuery(validationQuery); //用來檢測連接是否有效的sql,要求是一個(gè)查詢語句。如果validationQuery為null,testOnBorrow、testOnReturn、testWhileIdle都不會(huì)起作用。druidDataSource.setFilters("stat");//屬性類型是字符串,通過別名的方式配置擴(kuò)展插件,常用的插件有:監(jiān)控統(tǒng)計(jì)用的filter:stat日志用的filter:log4j防御sql注入的filter:walldruidDataSource.setTimeBetweenEvictionRunsMillis(60000); //配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒druidDataSource.setMinEvictableIdleTimeMillis(180000); //配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒,這里配置為3分鐘180000druidDataSource.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)做?;顧z測,不會(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賦值給父類的TargetDataSourcessuper.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; } }
定義注解
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})@Documentedpublic @interface TargetDataSource {String value() default "master"; //該值即key值}
public class DBContextHolder {private static Logger log = LoggerFactory.getLogger(DBContextHolder.class);// 對(duì)當(dāng)前線程的操作-線程安全的private static final ThreadLocalcontextHolder = new ThreadLocal ();// 調(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)類
@Aspect@Component@Order(Ordered.HIGHEST_PRECEDENCE)public class DruidDBAspect {private static Logger logger = LoggerFactory.getLogger(DruidDBAspect.class);@Autowiredprivate 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)的庫傳參
@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關(guān)于springboot中怎么配置多數(shù)據(jù)源就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
文章題目:springboot中怎么配置多數(shù)據(jù)源
當(dāng)前路徑:http://weahome.cn/article/iepcei.html