ToB企服应用市场:ToB评测及商务社交产业平台

标题: java设置多数据源 [打印本页]

作者: 李优秀    时间: 2025-1-5 10:23
标题: java设置多数据源
三个数据库:master主库、back_one从库1、back_two从库2
1.application.yml设置三个数据库信息

  1. spring:
  2.   datasource:
  3.     driver-class-name : com.mysql.jdbc.Driver
  4.     # 主库
  5.     master:
  6.       jdbcUrl : jdbc:mysql://xxx:3306/master?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2b8&allowMultiQueries=true
  7.       username : xxx
  8.       password : xxx
  9.       name :
  10.     # 从库1
  11.     slave:
  12.       enabled: true  # 从数据源开关/默认关闭
  13.       jdbcUrl: jdbc:mysql://xxx:3306/back_one?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=GMT%2b8
  14.       username: xxx
  15.       password: xxx
  16.       name :
  17.     # 从库2
  18.     slave2:
  19.       enabled: true  # 从数据源开关/默认关闭
  20.       jdbcUrl: jdbc:mysql://xxx:3306/back_two?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=GMT%2b8
  21.       username: xxx
  22.       password: xxx
  23.       name :
  24.     druid.maxActive : 150
  25.     druid.initialSize : 5
  26.     druid.minIdle : 5
  27.     druid.maxWait : 60000
  28.     druid.filters : stat
  29.     druid.timeBetweenEvictionRunsMillis : 60000
  30.     druid.minEvictableIdleTimeMillis : 300000
  31.     druid.validationQuery : SELECT 1    #多个数据源时配置:select count(*) from dual
  32.     druid.testWhileIdle : true
  33.     druid.testOnBorrow : false
  34.     druid.testOnReturn : false
  35.     druid.poolPreparedStatements : false
  36.     druid.maxPoolPreparedStatementPerConnectionSize : -1
  37.     druid.timeBetweenLogStatsMillis : 0
  38.     druid.keep-alive : true
  39.     druid.connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;druid.stat.logSlowSql=true
复制代码
注意:
一个数据源时:validationQuery: SELECT 1;
多个数据源时:validationQuery: select count(*) from dual
2.代码

(1)DataSource

  1. import java.lang.annotation.*;
  2. @Target(ElementType.TYPE)
  3. @Retention(RetentionPolicy.RUNTIME)
  4. @Documented
  5. public @interface DataSource {
  6.     DataSourceType value() default DataSourceType.MASTER;
  7. }
复制代码
(2)DataSourceAspect

  1. import org.aspectj.lang.JoinPoint;
  2. import org.aspectj.lang.annotation.After;
  3. import org.aspectj.lang.annotation.Aspect;
  4. import org.aspectj.lang.annotation.Before;
  5. import org.aspectj.lang.annotation.Pointcut;
  6. import org.aspectj.lang.reflect.MethodSignature;
  7. import org.springframework.core.annotation.Order;
  8. import org.springframework.stereotype.Component;
  9. import java.lang.reflect.Method;
  10. @Aspect
  11. @Order(1)
  12. @Component
  13. public class DataSourceAspect {
  14.     @Pointcut("execution(public * com.xxx.mapper..*.*(..))")
  15.     public void pointcut() {}
  16.     @Before("pointcut()")
  17.     public void doBefore(JoinPoint joinPoint)
  18.     {
  19.         Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
  20.         DataSource dataSource = method.getAnnotation(DataSource.class);  //获取方法上的注解
  21.         if(dataSource == null){
  22.             Class<?> clazz= joinPoint.getTarget().getClass().getInterfaces()[0];
  23.             dataSource =clazz.getAnnotation(DataSource.class);  //获取类上面的注解
  24.             if(dataSource == null) return;
  25.         }
  26.         if (dataSource != null) {
  27.             DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
  28.         }
  29.     }
  30.     @After("pointcut()")
  31.     public void after(JoinPoint point) {
  32.         //清理掉当前设置的数据源,让默认的数据源不受影响
  33.         DynamicDataSourceContextHolder.clearDataSourceType();
  34.     }
  35. }
复制代码
(3)DataSourceConfig

  1. import com.alibaba.druid.pool.DruidDataSource;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.context.annotation.DependsOn;
  7. import org.springframework.context.annotation.Primary;
  8. import javax.sql.DataSource;
  9. import java.sql.SQLException;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. @Configuration
  13. public class DataSourceConfig {
  14.     //主数据源
  15.     @Value("${spring.datasource.master.jdbcUrl}")
  16.     private String masterJdbcUrl;
  17.     @Value("${spring.datasource.master.username}")
  18.     private String masterUsername;
  19.     @Value("${spring.datasource.master.password}")
  20.     private String masterPassword;
  21.     @Value("${spring.datasource.driver-class-name}")
  22.     private String masterDriverClassName;
  23.     @Value("${spring.datasource.master.name}")
  24.     private String name;
  25.     //从数据源1
  26.     @Value("${spring.datasource.slave.jdbcUrl}")
  27.     private String slaveJdbcUrl1;
  28.     @Value("${spring.datasource.slave.username}")
  29.     private String slaveUsername1;
  30.     @Value("${spring.datasource.slave.password}")
  31.     private String slavePassword1;
  32.     @Value("${spring.datasource.driver-class-name}")
  33.     private String slaveDriverClassName1;
  34.     @Value("${spring.datasource.slave.name}")
  35.     private String slaveName;
  36.     //从数据源2
  37.     @Value("${spring.datasource.slave2.jdbcUrl}")
  38.     private String slaveJdbcUrl2;
  39.     @Value("${spring.datasource.slave2.username}")
  40.     private String slaveUsername2;
  41.     @Value("${spring.datasource.slave2.password}")
  42.     private String slavePassword2;
  43.     @Value("${spring.datasource.driver-class-name}")
  44.     private String slaveDriverClassName2;
  45.     @Value("${spring.datasource.slave2.name}")
  46.     private String slaveName2;
  47.     //其他相关配置
  48.     @Value("${spring.datasource.druid.initialSize}")
  49.     private int initialSize;
  50.     @Value("${spring.datasource.druid.minIdle}")
  51.     private int minIdle;
  52.     @Value("${spring.datasource.druid.maxWait}")
  53.     private int maxWait;
  54.     @Value("${spring.datasource.druid.filters}")
  55.     private String filters;
  56.     @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
  57.     private int timeBetweenEvictionRunsMillis;
  58.     @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
  59.     private int minEvictableIdleTimeMillis;
  60.     @Value("${spring.datasource.druid.validationQuery}")
  61.     private String validationQuery;
  62.     @Value("${spring.datasource.druid.testWhileIdle}")
  63.     private boolean testWhileIdle;
  64.     @Value("${spring.datasource.druid.testOnBorrow}")
  65.     private boolean testOnBorrow;
  66.     @Value("${spring.datasource.druid.testOnReturn}")
  67.     private boolean testOnReturn;
  68.     @Value("${spring.datasource.druid.poolPreparedStatements}")
  69.     private boolean poolPreparedStatements;
  70.     @Value("${spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize}")
  71.     private int maxPoolPreparedStatementPerConnectionSize;
  72.     @Value("${spring.datasource.druid.timeBetweenLogStatsMillis}")
  73.     private int timeBetweenLogStatsMillis;
  74.     @Value("${spring.datasource.druid.keep-alive}")
  75.     private boolean keepAlive;
  76.     @Value("${spring.datasource.druid.connectionProperties}")
  77.     private String connectionProperties;
  78.     @Bean
  79.     public DataSource masterDataSource() {
  80.         return generateDataSource(masterJdbcUrl,masterUsername,masterPassword,masterDriverClassName,name);
  81.     }
  82.     @Bean
  83.     @ConditionalOnProperty(prefix = "spring.datasource.slave", name = "enabled", havingValue = "true")
  84.     public DataSource slaveDataSource1() {
  85.         return generateDataSource(slaveJdbcUrl1,slaveUsername1,slavePassword1,slaveDriverClassName1,slaveName);
  86.     }
  87.     @Bean
  88.     @ConditionalOnProperty(prefix = "spring.datasource.slave2", name = "enabled", havingValue = "true")
  89.     public DataSource slaveDataSource2() {
  90.         return generateDataSource(slaveJdbcUrl2,slaveUsername2,slavePassword2,slaveDriverClassName2,slaveName2);
  91.     }
  92.     private DruidDataSource generateDataSource(String url,String username,String password,String driverClassName,String name){
  93.         DruidDataSource datasource = new DruidDataSource();
  94.         datasource.setUrl(url);
  95.         datasource.setUsername(username);
  96.         datasource.setPassword(password);
  97.         datasource.setDriverClassName(driverClassName);
  98.         datasource.setName(name);
  99.         datasource.setInitialSize(initialSize);
  100.         datasource.setMinIdle(minIdle);
  101.         datasource.setMaxWait(maxWait);
  102.         datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  103.         datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  104.         datasource.setValidationQuery(validationQuery);
  105.         datasource.setTestWhileIdle(testWhileIdle);
  106.         datasource.setTestOnBorrow(testOnBorrow);
  107.         datasource.setTestOnReturn(testOnReturn);
  108.         datasource.setPoolPreparedStatements(poolPreparedStatements);
  109.         datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  110.         datasource.setKeepAlive(keepAlive);
  111.         try {
  112.             datasource.setFilters(filters);
  113.         } catch (SQLException e) {
  114.             System.err.println("druid configuration initialization filter: " + e);
  115.         }
  116.         datasource.setConnectionProperties(connectionProperties);
  117.         datasource.setTimeBetweenLogStatsMillis(timeBetweenLogStatsMillis);
  118.         return datasource;
  119.     }
  120.     @Bean(name = "dynamicDataSource")
  121.     @DependsOn({"masterDataSource", "slaveDataSource1", "slaveDataSource2"})  //如果不加这个,会报错:The dependencies of some of the beans in the application context form a cycle
  122.     @Primary
  123.     public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource1, DataSource slaveDataSource2) {
  124.         Map<Object, Object> targetDataSources = new HashMap<>();
  125.         targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
  126.         targetDataSources.put(DataSourceType.BACKONE.name(), slaveDataSource1);
  127.         targetDataSources.put(DataSourceType.BACKTWO.name(), slaveDataSource2);
  128.         return new DynamicDataSource(masterDataSource, targetDataSources);
  129.     }
  130. }
复制代码
(4)DataSourceType

  1. public enum DataSourceType {
  2.     /**
  3.      * 主库
  4.      */
  5.     MASTER,
  6.     /**
  7.      * 从库1
  8.      */
  9.     BACKONE,
  10.     /**
  11.      * 从库2
  12.      */
  13.     BACKTWO;
  14. }
复制代码
(5)DynamicDataSource

  1. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
  2. import javax.sql.DataSource;
  3. import java.util.Map;
  4. public class DynamicDataSource extends AbstractRoutingDataSource {
  5.     public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
  6.         super.setDefaultTargetDataSource(defaultTargetDataSource);
  7.         super.setTargetDataSources(targetDataSources);
  8.         // afterPropertiesSet()方法调用时用来将targetDataSources的属性写入resolvedDataSources中的
  9.         super.afterPropertiesSet();
  10.     }
  11.     /**
  12.      * 根据Key获取数据源的信息
  13.      */
  14.     @Override
  15.     protected Object determineCurrentLookupKey() {
  16.         return DynamicDataSourceContextHolder.getDataSourceType();
  17.     }
  18. }
复制代码
(6)DynamicDataSourceContextHolder

  1. import org.slf4j.Logger;
  2. import org.slf4j.LoggerFactory;
  3. public class DynamicDataSourceContextHolder {
  4.     public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);
  5.     /**
  6.      * 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
  7.      *  所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
  8.      */
  9.     private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
  10.     /**
  11.      * 设置数据源变量
  12.      */
  13.     public static void setDataSourceType(String dataSourceType){
  14.         log.info("切换到{}数据源", dataSourceType);
  15.         CONTEXT_HOLDER.set(dataSourceType);
  16.     }
  17.     /**
  18.      * 获取数据源变量
  19.      */
  20.     public static String getDataSourceType(){
  21.         return CONTEXT_HOLDER.get();
  22.     }
  23.     /**
  24.      * 清空数据源变量
  25.      */
  26.     public static void clearDataSourceType(){
  27.         CONTEXT_HOLDER.remove();
  28.     }
  29. }
复制代码
3.使用

(1)调用从库1

  1. /**
  2. * 调用从库1
  3. */
  4. @Component
  5. @DataSource(value = DataSourceType.BACKONE)
  6. public interface TestOneMapper {
  7. }
复制代码
(2)调用从库2

  1. /**
  2. * 调用从库2
  3. */
  4. @Component
  5. @DataSource(value = DataSourceType.BACKTWO)
  6. public interface TestTwoMapper {
  7. }
复制代码
欢迎关注我的公众号



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4