SpringBoot Mybatis 多数据源配置 注解方式切换数据源

一、自定义注解介绍
二、SpringBoot Mybatis 多数据源配置 注解方式切换数据源

2.1、通过SpringBoot+Mybatis多数据源配置实现多数据源连接,采用注解方式,支持任意数据库,默认使用原数据库,原有代码无需变更

2.2、Application新增注解,排除DataSourceAutoConfiguration,手动配置数据源

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

2.3、修改application.yml数据库配置

spring:
  datasource:
    master:
      url: jdbc:postgresql://65.26.12.127:25308/db_tzdd
      username: puser_tzdd
      password: 123456
      driver-class-name: org.postgresql.Driver
    slave:
      jdbc-url: jdbc:mysql://65.26.2.141:3306/hn_eis?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
      username: root
      password: 123456
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver

2.4、DataSourceConfig读取数据库配置,手动配置数据源

package com.example.testways.config.db;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Autowired
    private Environment env;

    /**
     *  65.38.37.235为主数据库
     *  主数据库配置
     */
    @Bean("master")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource(){
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName(env.getProperty("spring.datasource.master.driver-class-name"));
        dataSourceBuilder.url(env.getProperty("spring.datasource.master.url"));
        dataSourceBuilder.username(env.getProperty("spring.datasource.master.username"));
        dataSourceBuilder.password(env.getProperty("spring.datasource.master.password"));
        return dataSourceBuilder.build();
    }

    /**
     *  65.38.37.141 为从数据库
     *  从数据库配置
     */
    @Bean("slave")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource(){
        return DataSourceBuilder.create().build();
    }


    /**
     *  动态数据源配置
     */
    @Primary
    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource(){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //默认数据源
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource());

        //配置多数据源
        Map<Object, Object> dsMap = new HashMap<Object, Object>(5);
        dsMap.put("master", masterDataSource());
        dsMap.put("slave", slaveDataSource());
        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }

    /**
     * 配置@Transactional注解事物
     *  @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dynamicDataSource());
    }
}

2.5、配置DataSourceContextHolder上下文

package com.example.testways.config.db;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DataSourceContextHolder {
    // 默认数据源
    public static final String DEFAULT_DS = "master";

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static void setDB(String dbType) {
        log.info("切换至" + dbType + "数据源");
        contextHolder.set(dbType);
    }

    public static String getDB() {
        return (contextHolder.get());
    }

    public static void clearDB() {
        contextHolder.remove();
    }
}

2.6、动态数据源配置

package com.example.testways.config.db;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDB();
    }
}

2.7、注解方式配置

package com.example.testways.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataBase {
    String value() default "master";
}

2.8、切面
@Pointcut: 注解的值为上述自定义注解DataBase 的路径

package com.example.testways.config.db;


import com.example.testways.annotation.DataBase;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DataBaseAspect {

    @Pointcut("@annotation(com.example.testways.annotation.DataBase)")
    public void dbPointCut(){

    }

    @Before("dbPointCut()")
    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);

                // 判断是否存在@DateBase注解
                if (method.isAnnotationPresent(DataBase.class)) {
                    DataBase annotation = method.getAnnotation(DataBase.class);
                    // 取出注解中的数据源名
                    dataSource = annotation.value();
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 切换数据源
        DataSourceContextHolder.setDB(dataSource);
    }

    @After("dbPointCut()")
    public void afterSwitchDS(JoinPoint point){
        DataSourceContextHolder.clearDB();
    }
}

2.9、以上即为全部配置内容,使用时,在service层方法上调用@DataBase注解,无注解时,使用默认数据源。

你可能感兴趣的:(mybatis,spring,boot,数据库)