spring boot 注解方式配置多数据源与使用

1、首先看一下application-dev.yml 配置

spring:

    datasource:

        type: com.alibaba.druid.pool.DruidDataSource

        druid:

            first:  #数据源1

                driverClassName: com.mysql.jdbc.Driver

                url: jdbc:mysql://127.0.0.1:3306/xujl?useUnicode=true&characterEncoding=UTF-8

               username: root

                password: admin

            second:  #数据源2

                url: jdbc:postgresql://172.xx.x.xx:xxxx/pcsu?charSet=utf-8

                username: suit_test

                password: suit_test

                driverClassName: org.postgresql.Driver

            initial-size: 10

            max-active: 100

            min-idle: 10

           max-wait: 60000

            pool-prepared-statements: true

            max-pool-prepared-statement-per-connection-size: 20

            time-between-eviction-runs-millis: 60000

            min-evictable-idle-time-millis: 300000

            validation-query: SELECT 1 FROM DUAL

            test-while-idle: true

            test-on-borrow: false

            test-on-return: false

            stat-view-servlet:

                enabled: true

                url-pattern: /druid/*

                #login-username: admin

                #login-password: admin

            filter:

                stat:

                    log-slow-sql: true

                    slow-sql-millis: 1000

                    merge-sql: true

                wall:

                    config:

                       multi-statement-allow: true

上面的方式实现就已经配置了两个 数据源了,下面来看下代码的实现

2、配置一个注解,方便使用,直接在需要配置的方法上面加上数据源即可

@Target({ ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface DataSource {

    String name() default "";

}

2-1:配置管理多数据源的名称,方便管理。

  1. /**
  2.  * 增加多数据源,在此配置
  3.  */
  4. public interface DataSourceNames {
  5.     String FIRST = "first";
  6.     String SECOND = "second";
  7. }

3、动态数据源加载

  1. /**
  2.  * 动态数据源
  3.  */
  4. public class DynamicDataSource extends AbstractRoutingDataSource {
  5.     //用来保存数据源与获取数据源
  6.     private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
  7.  
  8.     public DynamicDataSource(DataSource defaultTargetDataSource, Map<String, DataSource> targetDataSources) {
  9.         super.setDefaultTargetDataSource(defaultTargetDataSource);
  10.         super.setTargetDataSources(new HashMap<Object, Object>(targetDataSources));
  11.         super.afterPropertiesSet();
  12.     }
  13.  
  14.     @Override
  15.     protected Object determineCurrentLookupKey() {
  16.         return getDataSource();
  17.     }
  18.  
  19.     public static void setDataSource(String dataSource) {
  20.         contextHolder.set(dataSource);
  21.     }
  22.  
  23.     public static String getDataSource() {
  24.         return contextHolder.get();
  25.     }
  26.  
  27.     public static void clearDataSource() {
  28.         contextHolder.remove();
  29.     }
  30.  
  31. }

这里有必要说一下AbstractRoutingDataSource这个类,加载一个图片:

可以看到AbstractRoutingDataSource获取数据源之前会先调用determineCurrentLookupKey方法查找当前的lookupKey,这个lookupKey就是数据源标识。

因此通过重写这个查找数据源标识的方法就可以让spring切换到指定的数据源了。

(这张图片出自:点击打开链接 尊重原创。)

3-1:重要一点:吧上面的信心加载到配置中

  1. /**
  2.  * 配置多数据源
  3.  */
  4. @Configuration
  5. public class DynamicDataSourceConfig {
  6.  
  7.     @Bean
  8.     @ConfigurationProperties("spring.datasource.druid.first")
  9.     public DataSource firstDataSource(){
  10.         return DruidDataSourceBuilder.create().build();
  11.     }
  12.  
  13.     @Bean
  14.     @ConfigurationProperties("spring.datasource.druid.second")
  15.     public DataSource secondDataSource(){
  16.         return DruidDataSourceBuilder.create().build();
  17.     }
  18.  
  19.     @Bean
  20.     @Primary
  21.     public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
  22.         Map<String, DataSource> targetDataSources = new HashMap<>();
  23.         targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
  24.         targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
  25.         return new DynamicDataSource(firstDataSource, targetDataSources);
  26.     }
  27. }

4、最最重要的一步,就是使用spring的aop原理,切面方式加载数据源

  1. /**
  2.  * 多数据源,切面处理类 处理带有注解的方法类
  3.  */
  4. @Aspect
  5. @Component
  6. public class DataSourceAspect implements Ordered {
  7.  
  8. protected Logger logger = LoggerFactory.getLogger(getClass());
  9.  
  10. @Pointcut("@annotation(xxxx.DataSource)")//注意:这里的xxxx代表的是上面public @interface DataSource这个注解DataSource的包名
  11. public void dataSourcePointCut() {
  12.  
  13. }
  14.  
  15. @Around("dataSourcePointCut()")
  16. public Object around(ProceedingJoinPoint point) throws Throwable {
  17. MethodSignature signature = (MethodSignature) point.getSignature();
  18. Method method = signature.getMethod();
  19. DataSource ds = method.getAnnotation(DataSource.class);
  20. if (ds == null) {
  21. DynamicDataSource.setDataSource(DataSourceNames.FIRST);
  22. logger.debug("set datasource is " + DataSourceNames.FIRST);
  23.            } else {
  24. DynamicDataSource.setDataSource(ds.name());
  25. logger.debug("set datasource is " + ds.name());
  26. }
  27. try {
  28. return point.proceed();
  29.            } finally {
  30. DynamicDataSource.clearDataSource();
  31. logger.debug("clean datasource");
  32. }
  33. }
  34.  
  35.  
  36.  
  37. @Override
  38. public int getOrder() {
  39. return 1;
  40. }
  41. }

5、最后一步就是使用了在你的service的实现类 serviceImpl上面进行注解,这里是重点(我刚开一直放在dao上面,因为我用的是mybatis,以为就是要放在这个上面,结果一直出不来,最后才知道应该放在serviceImpl上面)@Override

  1. @DataSource(name="second")
  2. public List<IntegralExchangeRule> list(Map<String,Object> map) {
  3. return dao.list(map);
  4. }

OK,现在已经全部配置完成,可以使用了

有必要说一下:我上面的DataSourceAspect这个类里面around方法里面,已经默认是数据源1,如果你不配置@DaeSource(name=""),它默认会使用第一个数据源,否则的话,按照你的数据源名称去使用的。;

 

**欢迎关注我的个人公众号:we-aibook,里面有相关技术文章分享,项目架构,知识星球,技术交流群,不定期进行抽奖送书活动哟!**

猜你喜欢

转载自blog.csdn.net/lsjinjin/article/details/84647032