溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

springboot實(shí)現(xiàn)多數(shù)據(jù)源配置及切換

發(fā)布時(shí)間:2020-11-02 17:10:44 來(lái)源:億速云 閱讀:235 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)springboot實(shí)現(xiàn)多數(shù)據(jù)源配置及切換,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

配置文件數(shù)據(jù)源讀取

通過(guò)springboot的Envioment和Binder對(duì)象進(jìn)行讀取,無(wú)需手動(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ù)庫(kù)必須配置,cluster下的為從庫(kù),選擇性配置

獲取配置文件信息代碼如下

@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)

public interface ExtraDataSourceService {
 List<DataSourceModel> getExtraDataSourc();
}

獲取對(duì)應(yīng)Service的所有實(shí)現(xiàn)類(lèi)進(jìn)行調(diào)用

 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;
 }

通過(guò)代碼進(jìn)行數(shù)據(jù)源注冊(cè)

主要是用過(guò)繼承類(lèi)AbstractRoutingDataSource,重寫(xiě)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ù)庫(kù)
   } 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í)間過(guò)長(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è)連接是否有效,這里建議配置為T(mén)RUE,防止取到的連接不可用
   druidDataSource.setTestWhileIdle(true);//建議配置為true,不影響性能,并且保證安全性。申請(qǐng)連接的時(shí)候檢測(cè),如果空閑時(shí)間大于timeBetweenEvictionRunsMillis,執(zhí)行validationQuery檢測(cè)連接是否有效。
   druidDataSource.setValidationQuery(validationQuery); //用來(lái)檢測(cè)連接是否有效的sql,要求是一個(gè)查詢(xún)語(yǔ)句。如果validationQuery為null,testOnBorrow、testOnReturn、testWhileIdle都不會(huì)起作用。
   druidDataSource.setFilters("stat");//屬性類(lèi)型是字符串,通過(guò)別名的方式配置擴(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); //打開(kāi)druid.keepAlive之后,當(dāng)連接池空閑時(shí),池中的minIdle數(shù)量以?xún)?nèi)的連接,空閑時(shí)間超過(guò)minEvictableIdleTimeMillis,則會(huì)執(zhí)行keepAlive操作,即執(zhí)行druid.validationQuery指定的查詢(xún)SQL,一般為select * from dual,只要minEvictableIdleTimeMillis設(shè)置的小于防火墻切斷連接時(shí)間,就可以保證當(dāng)連接空閑時(shí)自動(dòng)做?;顧z測(cè),不會(huì)被防火墻切斷
   druidDataSource.setRemoveAbandoned(true); //是否移除泄露的連接/超過(guò)時(shí)間限制是否回收。
   druidDataSource.setRemoveAbandonedTimeout(3600); //泄露連接的定義時(shí)間(要超過(guò)最大事務(wù)的處理時(shí)間);單位為秒。這里配置為1小時(shí)
   druidDataSource.setLogAbandoned(true); //移除泄露連接發(fā)生是是否記錄日志
   druidDataSource.init();
   this.dynamicTargetDataSources.put(key, druidDataSource);
   setTargetDataSources(this.dynamicTargetDataSources);// 將map賦值給父類(lèi)的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;
  }
 }

通過(guò)切面注解統(tǒng)一切換

定義注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
@Documented
public @interface TargetDataSource {
 String value() default "master"; //該值即key值
}

定義基于線(xiàn)程的切換類(lèi)

public class DBContextHolder {
 private static Logger log = LoggerFactory.getLogger(DBContextHolder.class);
 // 對(duì)當(dāng)前線(xiàn)程的操作-線(xiàn)程安全的
 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í)高于類(lèi)注解,一般用于Service的實(shí)現(xiàn)類(lèi)

@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();
  }
 }
}

分庫(kù)切換

開(kāi)發(fā)過(guò)程中某個(gè)庫(kù)的某個(gè)表做了拆分操作,相同的某一次數(shù)據(jù)庫(kù)操作可能對(duì)應(yīng)到不同的庫(kù),需要對(duì)方法級(jí)別進(jìn)行精確攔截,可以定義一個(gè)業(yè)務(wù)層面的切面,規(guī)定每個(gè)方法必須第一個(gè)參數(shù)為dbName,根據(jù)具體業(yè)務(wù)找到對(duì)應(yīng)的庫(kù)傳參

@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í)現(xiàn)多數(shù)據(jù)源配置及切換就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI