一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Spring Boot + Mybatis多數據源和動態數據源配置方法

Spring Boot + Mybatis多數據源和動態數據源配置方法

2021-03-23 13:51司青 Java教程

最近做項目遇到這樣的應用場景,項目需要同時連接兩個不同的數據庫A, B,并且它們都為主從架構,一臺寫庫,多臺讀庫。下面小編給大家帶來了Spring Boot + Mybatis多數據源和動態數據源配置方法,需要的朋友參考下吧

網上的文章基本上都是只有多數據源或只有動態數據源,而最近的項目需要同時使用兩種方式,記錄一下配置方法供大家參考。

應用場景

項目需要同時連接兩個不同的數據庫A, B,并且它們都為主從架構,一臺寫庫,多臺讀庫。

多數據源

首先要將spring boot自帶的DataSourceAutoConfiguration禁掉,因為它會讀取application.properties文件的spring.datasource.*屬性并自動配置單數據源。在@SpringBootApplication注解中添加exclude屬性即可:

?
1
2
3
4
5
6
7
8
@SpringBootApplication(exclude = {
  DataSourceAutoConfiguration.class
})
public class TitanWebApplication {
 public static void main(String[] args) {
  SpringApplication.run(TitanWebApplication.class, args);
 }
}

然后在application.properties中配置多數據源連接信息:

?
1
2
3
4
5
6
7
8
9
10
11
12
# titan庫
spring.datasource.titan-master.url=jdbc:mysql://X.X.X.X:port/titan?characterEncoding=UTF-8
spring.datasource.titan-master.username=
spring.datasource.titan-master.password=
spring.datasource.titan-master.driver-class-name=com.mysql.jdbc.Driver
# 連接池配置
# 省略
# 其它庫
spring.datasource.db2.url=jdbc:mysql://X.X.X.X:port/titan2?characterEncoding=UTF-8
spring.datasource.db2.username=
spring.datasource.db2.password=
spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver

由于我們禁掉了自動數據源配置,因些下一步就需要手動將這些數據源創建出來:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
public class DataSourceConfig {
 @Bean(name = "titanMasterDS")
 @ConfigurationProperties(prefix = "spring.datasource.titan-master") // application.properteis中對應屬性的前綴
 public DataSource dataSource1() {
  return DataSourceBuilder.create().build();
 }
 @Bean(name = "ds2")
 @ConfigurationProperties(prefix = "spring.datasource.db2") // application.properteis中對應屬性的前綴
 public DataSource dataSource2() {
  return DataSourceBuilder.create().build();
 }
}

接下來需要配置兩個mybatis的SqlSessionFactory分別使用不同的數據源:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
@MapperScan(basePackages = {"titan.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class MybatisDbAConfig {
 @Autowired
 @Qualifier("titanMasterDS")
 private DataSource ds1;
 @Bean
 public SqlSessionFactory sqlSessionFactory1() throws Exception {
  SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  factoryBean.setDataSource(ds1); // 使用titan數據源, 連接titan庫
  return factoryBean.getObject();
 }
 @Bean
 public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
  SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); // 使用上面配置的Factory
  return template;
 }
}

經過上面的配置后,titan.mapper下的Mapper接口,都會使用titan數據源。同理可配第二個SqlSessionFactory:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
@MapperScan(basePackages = {"other.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisDbBConfig {
 @Autowired
 @Qualifier("ds2")
 private DataSource ds2;
 @Bean
 public SqlSessionFactory sqlSessionFactory2() throws Exception {
  SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  factoryBean.setDataSource(ds2);
  return factoryBean.getObject();
 }
 @Bean
 public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
  SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());
  return template;
 }
}

完成這些配置后,假設有2個Mapper titan.mapper.UserMapper和other.mapper.RoleMapper,使用前者時會自動連接titan庫,后者連接ds2庫。

動態數據源

使用動態數據源的初衷,是能在應用層做到讀寫分離,即在程序代碼中控制不同的查詢方法去連接不同的庫。除了這種方法以外,數據庫中間件也是個不錯的選擇,它的優點是數據庫集群對應用來說只暴露為單庫,不需要切換數據源的代碼邏輯。

我們通過自定義注解 + AOP的方式實現數據源動態切換。

首先定義一個ContextHolder, 用于保存當前線程使用的數據源名:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class DataSourceContextHolder {
 public static final Logger log = LoggerFactory.getLogger(DataSourceContextHolder.class);
 /**
  * 默認數據源
  */
 public static final String DEFAULT_DS = "titan-master";
 private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
 // 設置數據源名
 public static void setDB(String dbType) {
  log.debug("切換到{}數據源", dbType);
  contextHolder.set(dbType);
 }
 // 獲取數據源名
 public static String getDB() {
  return (contextHolder.get());
 }
 // 清除數據源名
 public static void clearDB() {
  contextHolder.remove();
 }
}

然后自定義一個javax.sql.DataSource接口的實現,這里只需要繼承Spring為我們預先實現好的父類AbstractRoutingDataSource即可:

?
1
2
3
4
5
6
7
8
public class DynamicDataSource extends AbstractRoutingDataSource {
 private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);
 @Override
 protected Object determineCurrentLookupKey() {
  log.debug("數據源為{}", DataSourceContextHolder.getDB());
  return DataSourceContextHolder.getDB();
 }
}

創建動態數據源:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
  * 動態數據源: 通過AOP在不同數據源之間動態切換
  * @return
  */
 @Bean(name = "dynamicDS1")
 public DataSource dataSource() {
  DynamicDataSource dynamicDataSource = new DynamicDataSource();
  // 默認數據源
  dynamicDataSource.setDefaultTargetDataSource(dataSource1());
  // 配置多數據源
  Map<Object, Object> dsMap = new HashMap(5);
  dsMap.put("titan-master", dataSource1());
  dsMap.put("ds2", dataSource2());
  dynamicDataSource.setTargetDataSources(dsMap);
  return dynamicDataSource;
 }

自定義注釋@DS用于在編碼時指定方法使用哪個數據源:

?
1
2
3
4
5
6
7
@Retention(RetentionPolicy.RUNTIME)
@Target({
  ElementType.METHOD
})
public @interface DS {
 String value() default "titan-master";
}

編寫AOP切面,實現切換邏輯:

?
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
@Aspect
@Component
public class DynamicDataSourceAspect {
 @Before("@annotation(DS)")
 public void beforeSwitchDS(JoinPoint point){
  //獲得當前訪問的class
  Class<?> className = point.getTarget().getClass();
  //獲得訪問的方法名
  String methodName = point.getSignature().getName();
  //得到方法的參數的類型
  Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
  String dataSource = DataSourceContextHolder.DEFAULT_DS;
  try {
   // 得到訪問的方法對象
   Method method = className.getMethod(methodName, argClass);
   // 判斷是否存在@DS注解
   if (method.isAnnotationPresent(DS.class)) {
    DS annotation = method.getAnnotation(DS.class);
    // 取出注解中的數據源名
    dataSource = annotation.value();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  // 切換數據源
  DataSourceContextHolder.setDB(dataSource);
 }
 @After("@annotation(DS)")
 public void afterSwitchDS(JoinPoint point){
  DataSourceContextHolder.clearDB();
 }
}

完成上述配置后,在先前SqlSessionFactory配置中指定使用DynamicDataSource就可以在Service中愉快的切換數據源了:

?
1
2
3
4
5
6
7
8
9
10
@Autowired
 private UserAModelMapper userAMapper;
 @DS("titan-master")
 public String ds1() {
  return userAMapper.selectByPrimaryKey(1).getName();
 }
 @DS("ds2")
 public String ds2() {
  return userAMapper.selectByPrimaryKey(1).getName();
 }

總結

以上所述是小編給大家介紹的Spring Boot + Mybatis多數據源和動態數據源配置方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!

原文鏈接:http://blog.csdn.net/neosmith/article/details/61202084

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日韩永久在线观看免费视频 | 日产乱码卡一卡2卡三卡四福利 | 精品AV无码一二三区视频 | 极品久久 | 91国在线观看 | 亚洲成人免费看 | bt岛www| 好逼天天有| 日本韩国无矿砖码 | 深夜福利免费观看 | 久久99re2在线视频精品 | 国产精品成人免费 | 日韩精品视频美在线精品视频 | 色综合图片 | 欧美肥b| 国产露脸对白刺激3p在线 | 欧美成人三级伦在线观看 | 99久久一香蕉国产线看观看 | 欧美日韩精品亚洲精品v18 | 亚洲视频免费 | 色婷婷网 | 粉嫩高中生第一次不戴套 | 欧美一级特黄特色大片 | 91极品在线观看 | 美女扒开腿让男生捅 | 亚洲午夜久久久久影院 | 欧美日韩1区2区 | 国产成人精品福利色多多 | 欧美亚洲第一区 | 欧美黑人性猛交╳xx╳动态图 | 国产欧美另类久久精品91 | 国内精品视频一区二区三区八戒 | 好吊色青青青国产综合在线观看 | 欧美视频一区二区三区四区 | 免费草比视频 | 逼逼毛片| 欧美va在线 | 四川女人偷人真实视频 | 3d美女触手怪爆羞羞漫画 | 皇上撞着太子妃的秘密小说 | 三级伦理在线播放 |