關於SpringBoot中的多數據源集成


引言

其實對於分庫分表這塊的場景,目前市場上有很多成熟的開源中間件,eg:MyCAT,Cobar,sharding-JDBC等。 

本文主要是介紹基於springboot的多數據源切換,輕量級的一種集成方案,對於小型的應用可以采用這種方案,我之前在項目中用到是因為簡單,便於擴展以及優化。

應用場景

假設目前我們有以下幾種數據訪問的場景: 
1.一個業務邏輯中對不同的庫進行數據的操作(可能你們系統不存在這種場景,目前都時微服務的架構,每個微服務基本上是對應一個數據庫比較多,其他的需要通過服務來方案。), 
2.訪問分庫分表的場景;后面的文章會單獨介紹下分庫分表的集成。

假設這里,我們以6個庫,每個庫1000張表的例子來介紹),因為隨着業務量的增長,一個庫很難抗住這么大的訪問量。比如說訂單表,我們可以根據userid進行分庫分表。 
分庫策略:userId%6[表的數量]; 
分庫分表策略:庫路由[userId/(6*1000)/1000],表路由[ userId/(6*1000)%1000].

集成方案

方案總覽: 
方案是基於springjdbc中提供的api實現,看下下面兩段代碼,是我們的切入點,我們都是圍繞着這2個核心方法進行集成的。

第一段代碼是注冊邏輯,會將defaultTargetDataSource和targetDataSources這兩個數據源對象注冊到resolvedDataSources中。

第二段是具體切換邏輯: 如果數據源為空,那么他就會找我們的默認數據源defaultTargetDataSource,如果設置了數據源,那么他就去讀這個值 Object lookupKey = determineCurrentLookupKey();我們后面會重寫這個方法。

我們會在配置文件中配置主數據源(默認數據源)和其他數據源,然后在應用啟動的時候注冊到spring容器中,分別給defaultTargetDataSource和targetDataSources進行賦值,進而進行Bean注冊。

真正的使用過程中,我們定義注解,通過切面,定位到當前線程是由訪問哪個數據源(維護着一個ThreadLocal的對象),進而調用determineCurrentLookupKey方法,進行數據源的切換。

 1 public void afterPropertiesSet() {
 2         if (this.targetDataSources == null) {
 3             throw new IllegalArgumentException("Property 'targetDataSources' is required");
 4         }
 5         this.resolvedDataSources = new HashMap<Object, DataSource>(this.targetDataSources.size());
 6         for (Map.Entry<Object, Object> entry : this.targetDataSources.entrySet()) {
 7             Object lookupKey = resolveSpecifiedLookupKey(entry.getKey());
 8             DataSource dataSource = resolveSpecifiedDataSource(entry.getValue());
 9             this.resolvedDataSources.put(lookupKey, dataSource);
10         }
11         if (this.defaultTargetDataSource != null) {
12             this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource);
13         }
14     }   
15 
16 @Override
17 public Connection getConnection() throws SQLException {
18         return determineTargetDataSource().getConnection();
19 }
20 
21 protected DataSource determineTargetDataSource() {
22         Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
23         Object lookupKey = determineCurrentLookupKey();
24         DataSource dataSource = this.resolvedDataSources.get(lookupKey);
25         if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
26             dataSource = this.resolvedDefaultDataSource;
27         }
28         if (dataSource == null) {
29             throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
30         }
31         return dataSource;
32     }

1.動態數據源注冊 注冊默認數據源以及其他額外的數據源; 這里只是復制了核心的幾個方法,具體的大家下載git看代碼。

 1  // 創建DynamicDataSource
 2         GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
 3         beanDefinition.setBeanClass(DyncRouteDataSource.class);
 4         beanDefinition.setSynthetic(true);
 5         MutablePropertyValues mpv = beanDefinition.getPropertyValues();
 6         //默認數據源
 7         mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource); 
 8         //其他數據源
 9         mpv.addPropertyValue("targetDataSources", targetDataSources);
10         //注冊到spring bean容器中
11         registry.registerBeanDefinition("dataSource", beanDefinition);

2.在Application中加載動態數據源,這樣spring容器啟動的時候就會將數據源加載到內存中。

1 @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, MybatisAutoConfiguration.class })
2 @Import(DyncDataSourceRegister.class)
3 @ServletComponentScan                                       
4 @ComponentScan(basePackages = { "com.happy.springboot.api","com.happy.springboot.service"})
5 public class Application {
6     public static void main(String[] args) {
7         SpringApplication.run(Application.class, args);
8     }
9 }

3.數據源切換核心邏輯:創建一個數據源切換的注解,並且基於該注解實現切面邏輯,這里我們通過threadLocal來實現線程間的數據源切換;

 1 import java.lang.annotation.Documented;
 2 import java.lang.annotation.ElementType;
 3 import java.lang.annotation.Retention;
 4 import java.lang.annotation.RetentionPolicy;
 5 import java.lang.annotation.Target;
 6 
 7 
 8 @Target({ ElementType.TYPE, ElementType.METHOD })
 9 @Retention(RetentionPolicy.RUNTIME)
10 @Documented
11 public @interface TargetDataSource {
12     String value();
13     // 是否分庫
14     boolean isSharding() default false;
15     // 獲取分庫策略
16     String strategy() default "";
17 }
18 
19 // 動態數據源上下文
20 public class DyncDataSourceContextHolder {
21 
22     private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
23 
24     public static List<String> dataSourceNames = new ArrayList<String>();
25 
26     public static void setDataSource(String dataSourceName) {
27         contextHolder.set(dataSourceName);
28     }
29 
30     public static String getDataSource() {
31         return contextHolder.get();
32     }
33 
34     public static void clearDataSource() {
35         contextHolder.remove();
36     }
37 
38     public static boolean containsDataSource(String dataSourceName) {
39         return dataSourceNames.contains(dataSourceName);
40     }
41 }
42 
43 /**
44  * 
45  * @author jasoHsu
46  * 動態數據源在切換,將數據源設置到ThreadLocal對象中
47  */
48 @Component
49 @Order(-10)
50 @Aspect
51 public class DyncDataSourceInterceptor {
52 
53     @Before("@annotation(targetDataSource)")
54     public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource) throws Exception {
55         String dbIndx = null;
56 
57         String targetDataSourceName = targetDataSource.value() + (dbIndx == null ? "" : dbIndx);
58         if (DyncDataSourceContextHolder.containsDataSource(targetDataSourceName)) {
59             DyncDataSourceContextHolder.setDataSource(targetDataSourceName);
60         }
61     }
62 
63     @After("@annotation(targetDataSource)")
64     public void resetDataSource(JoinPoint point, TargetDataSource targetDataSource) {
65         DyncDataSourceContextHolder.clearDataSource();
66     }
67 }
68 
69 //
70 public class DyncRouteDataSource extends AbstractRoutingDataSource {
71 @Override
72     protected Object determineCurrentLookupKey() {
73         return DyncDataSourceContextHolder.getDataSource();
74     }
75     public DataSource findTargetDataSource() {
76         return this.determineTargetDataSource();
77     }
78 }

4.與mybatis集成,其實這一步與前面的基本一致。 
只是將在sessionFactory以及數據管理器中,將動態數據源注冊進去【dynamicRouteDataSource】,而非之前的靜態數據源【getMasterDataSource()】

 1     @Resource
 2     DyncRouteDataSource dynamicRouteDataSource;
 3 
 4     @Bean(name = "sqlSessionFactory")
 5     public SqlSessionFactory getinvestListingSqlSessionFactory() throws Exception {
 6         String configLocation = "classpath:/conf/mybatis/configuration.xml";
 7         String mapperLocation = "classpath*:/com/happy/springboot/service/dao/*/*Mapper.xml";
 8         SqlSessionFactory sqlSessionFactory = createDefaultSqlSessionFactory(dynamicRouteDataSource, configLocation,
 9                 mapperLocation);
10 
11         return sqlSessionFactory;
12     }
13 
14 
15     @Bean(name = "txManager")
16     public PlatformTransactionManager txManager() {
17         return new DataSourceTransactionManager(dynamicRouteDataSource);
18     }

5.核心配置參數:

 1 spring:
 2   dataSource:
 3     happyboot:
 4       driverClassName: com.mysql.jdbc.Driver
 5       url: jdbc:mysql://localhost:3306/happy_springboot?characterEncoding=utf8&useSSL=true
 6       username: root
 7       password: admin
 8     extdsnames: happyboot01,happyboot02
 9     happyboot01:
10       driverClassName: com.mysql.jdbc.Driver
11       url: jdbc:mysql://localhost:3306/happyboot01?characterEncoding=utf8&useSSL=true
12       username: root
13       password: admin 
14     happyboot02:
15       driverClassName: com.mysql.jdbc.Driver
16       url: jdbc:mysql://localhost:3306/happyboot02?characterEncoding=utf8&useSSL=true
17       username: root
18       password: admin    

6.應用代碼

 1 @Service
 2 public class UserExtServiceImpl implements IUserExtService {
 3     @Autowired
 4     private UserInfoMapper userInfoMapper;
 5     @TargetDataSource(value="happyboot01")
 6     @Override
 7     public UserInfo getUserBy(Long id) {
 8         return userInfoMapper.selectByPrimaryKey(id);
 9     }
10 }

本文轉載自:https://blog.csdn.net/xuxian6823091/article/details/81051515

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM