欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot多數(shù)據(jù)源配置及切換的示例代碼詳解

 更新時間:2020年09月21日 08:35:23   作者:code2roc  
這篇文章主要介紹了springboot多數(shù)據(jù)源配置及切換,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

注:本文的多數(shù)據(jù)源配置及切換的實現(xiàn)方法是,在框架中封裝,具體項目中配置及使用,也適用于多模塊項目

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

通過springboot的Envioment和Binder對象進(jìn)行讀取,無需手動聲明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下的為從庫,選擇性配置

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

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

動態(tài)加入數(shù)據(jù)源

定義獲取數(shù)據(jù)源的Service,具體項目中進(jìn)行實現(xiàn)

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

獲取對應(yīng)Service的所有實現(xiàn)類進(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;
 }

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

主要是用過繼承類AbstractRoutingDataSource,重寫setTargetDataSources/setDefaultTargetDataSource方法

// 創(chuàng)建數(shù)據(jù)源
 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);// 相當(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ù)。初始化發(fā)生在顯示調(diào)用init方法,或者第一次getConnection時
   druidDataSource.setMaxActive(20); //最大連接池數(shù)量
   druidDataSource.setMaxWait(60000); //獲取連接時最大等待時間,單位毫秒。當(dāng)鏈接數(shù)已經(jīng)達(dá)到了最大鏈接數(shù)的時候,應(yīng)用如果還要獲取鏈接就會出現(xiàn)等待的現(xiàn)象,等待鏈接釋放并回到鏈接池,如果等待的時間過長就應(yīng)該踢掉這個等待,不然應(yīng)用很可能出現(xiàn)雪崩現(xiàn)象
   druidDataSource.setMinIdle(5); //最小連接池數(shù)量
   String validationQuery = "select 1 from dual";
   druidDataSource.setTestOnBorrow(true); //申請連接時執(zhí)行validationQuery檢測連接是否有效,這里建議配置為TRUE,防止取到的連接不可用
   druidDataSource.setTestWhileIdle(true);//建議配置為true,不影響性能,并且保證安全性。申請連接的時候檢測,如果空閑時間大于timeBetweenEvictionRunsMillis,執(zhí)行validationQuery檢測連接是否有效。
   druidDataSource.setValidationQuery(validationQuery); //用來檢測連接是否有效的sql,要求是一個查詢語句。如果validationQuery為null,testOnBorrow、testOnReturn、testWhileIdle都不會起作用。
   druidDataSource.setFilters("stat");//屬性類型是字符串,通過別名的方式配置擴展插件,常用的插件有:監(jiān)控統(tǒng)計用的filter:stat日志用的filter:log4j防御sql注入的filter:wall
   druidDataSource.setTimeBetweenEvictionRunsMillis(60000); //配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
   druidDataSource.setMinEvictableIdleTimeMillis(180000); //配置一個連接在池中最小生存的時間,單位是毫秒,這里配置為3分鐘180000
   druidDataSource.setKeepAlive(true); //打開druid.keepAlive之后,當(dāng)連接池空閑時,池中的minIdle數(shù)量以內(nèi)的連接,空閑時間超過minEvictableIdleTimeMillis,則會執(zhí)行keepAlive操作,即執(zhí)行druid.validationQuery指定的查詢SQL,一般為select * from dual,只要minEvictableIdleTimeMillis設(shè)置的小于防火墻切斷連接時間,就可以保證當(dāng)連接空閑時自動做?;顧z測,不會被防火墻切斷
   druidDataSource.setRemoveAbandoned(true); //是否移除泄露的連接/超過時間限制是否回收。
   druidDataSource.setRemoveAbandonedTimeout(3600); //泄露連接的定義時間(要超過最大事務(wù)的處理時間);單位為秒。這里配置為1小時
   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)一切換

定義注解

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

定義基于線程的切換類

public class DBContextHolder {
 private static Logger log = LoggerFactory.getLogger(DBContextHolder.class);
 // 對當(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)先級高于類注解,一般用于Service的實現(xiàn)類

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

分庫切換

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

到此這篇關(guān)于springboot多數(shù)據(jù)源配置及切換的示例代碼詳解的文章就介紹到這了,更多相關(guān)springboot多數(shù)據(jù)源配置 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java NIO 詳解

    java NIO 詳解

    Java NIO(New IO)是從Java 1.4版本開始引入的一個新的IO API,可以替代標(biāo)準(zhǔn)的Java IO API。本系列教程將有助于你學(xué)習(xí)和理解Java NIO。
    2014-10-10
  • SpringMVC?RESTFul及REST架構(gòu)風(fēng)格介紹

    SpringMVC?RESTFul及REST架構(gòu)風(fēng)格介紹

    這篇文章主要為大家介紹了SpringMVC?RESTFul及REST架構(gòu)風(fēng)格介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • Java中枚舉的使用詳解

    Java中枚舉的使用詳解

    這篇文章主要介紹了Java中枚舉的使用詳解的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-07-07
  • Springboot集成Spring Security實現(xiàn)JWT認(rèn)證的步驟詳解

    Springboot集成Spring Security實現(xiàn)JWT認(rèn)證的步驟詳解

    這篇文章主要介紹了Springboot集成Spring Security實現(xiàn)JWT認(rèn)證的步驟詳解,幫助大家更好的理解和使用springboot,感興趣的朋友可以了解下
    2021-02-02
  • IDEA中打jar包的2種方式(Maven打jar包)

    IDEA中打jar包的2種方式(Maven打jar包)

    這篇文章主要給大家介紹了關(guān)于IDEA中打jar包的2種方式,分別是不使用Maven直接打Jar包與使用Maven打jar包的兩種方法,需要的朋友可以參考下
    2021-05-05
  • 一個applicationContext 加載錯誤導(dǎo)致的阻塞問題及解決方法

    一個applicationContext 加載錯誤導(dǎo)致的阻塞問題及解決方法

    這篇文章主要介紹了一個applicationContext 加載錯誤導(dǎo)致的阻塞問題及解決方法,需要的朋友可以參考下
    2018-11-11
  • Java編程構(gòu)造方法與對象的創(chuàng)建詳解

    Java編程構(gòu)造方法與對象的創(chuàng)建詳解

    這篇文章主要介紹了Java編程構(gòu)造方法與對象的創(chuàng)建詳解,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • java equals和=,==的區(qū)別詳細(xì)介紹

    java equals和=,==的區(qū)別詳細(xì)介紹

    這篇文章主要介紹了java equals和=,==的區(qū)別,學(xué)習(xí)Java的朋友對equals 和== 這個概念開始使用的時候會有疑問,很難辨別如何正確使用,這里幫大家詳細(xì)講解該知識點,希望大家能掌握,有需要的小伙伴可以參考下
    2016-10-10
  • Mybatis基于xml配置實現(xiàn)單表的增刪改查功能

    Mybatis基于xml配置實現(xiàn)單表的增刪改查功能

    這篇文章主要介紹了Mybatis基于xml配置實現(xiàn)單表的增刪改查,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • java制作簡單驗證碼功能

    java制作簡單驗證碼功能

    這篇文章主要為大家詳細(xì)介紹了java制作簡單驗證碼功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-11-11

最新評論