菜单

springboot2动态数据源的绑定

2018年12月18日 - jQuery

是因为springboot2更新了绑定参数的api,部分springboot1用来绑定的家伙类如RelaxedPropertyResolver已经无力回天以初本子被利用。本文实现参考了https://blog.csdn.net/catoop/article/details/50575038顿时首著作,大致思路是同一的,假如欲详细实现好参见。都是透过AbstractRoutingDataSource实现动态数据源之切换,往日我因而spring配置多数据源的时候尽管经她实现之,有趣味之得领悟下其规律,这里就未多废话了。

摘要:springboot1.x到springboot2.0配备变化暴发某些变型,网上有关springboot2.0安排多数据源的资料为比少,为了吃我们安排多数据源从springboot1.x升级到springboot2.0少踩写坑,博主于斯介绍用springboot2.0来展开动态数据源切换。(在博客的终极会晤给我们提供源码的下载地址)

 

平等、引入倚重

废话不多说了,先上数据源注册工具类,springboot2与1底严重性分吧虽然当即时:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.heshouyou</groupId>
    <artifactId>dynamic-datasource</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>dynamic-datasource</name>
    <description>dynamic-datasource project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

MultiDataSourceRegister.java:

 

package top.ivan.demo.springboot.mapper;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.context.properties.source.ConfigurationPropertyNameAliases;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

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

public class MultiDataSourceRegister implements EnvironmentAware, ImportBeanDefinitionRegistrar {

    private final static ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); //别名

    static {
        //由于部分数据源配置不同,所以在此处添加别名,避免切换数据源出现某些参数无法注入的情况
        aliases.addAliases("url", new String[]{"jdbc-url"});
        aliases.addAliases("username", new String[]{"user"});
    }

    private Environment evn; //配置上下文(也可以理解为配置文件的获取工具)

    private Map<String, DataSource> sourceMap;  //数据源列表

    private Binder binder; //参数绑定工具

    /**
     * ImportBeanDefinitionRegistrar接口的实现方法,通过该方法可以按照自己的方式注册bean
     *
     * @param annotationMetadata
     * @param beanDefinitionRegistry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        Map config, properties, defaultConfig = binder.bind("spring.datasource", Map.class).get(); //获取所有数据源配置
        sourceMap = new HashMap<>(); //默认配置
        properties = defaultConfig;
        String typeStr = evn.getProperty("spring.datasource.type"); //默认数据源类型
        Class<? extends DataSource> clazz = getDataSourceType(typeStr); //获取数据源类型
        DataSource consumerDatasource, defaultDatasource = bind(clazz, properties); //绑定默认数据源参数
        List<Map> configs = binder.bind("spring.datasource.multi", Bindable.listOf(Map.class)).get(); //获取其他数据源配置
        for (int i = 0; i < configs.size(); i++) { //遍历生成其他数据源
            config = configs.get(i);
            clazz = getDataSourceType((String) config.get("type"));
            if ((boolean) config.getOrDefault("extend", Boolean.TRUE)) { //获取extend字段,未定义或为true则为继承状态
                properties = new HashMap(defaultConfig); //继承默认数据源配置
                properties.putAll(config); //添加数据源参数
            } else {
                properties = config; //不继承默认配置
            }
            consumerDatasource = bind(clazz, properties); //绑定参数
            sourceMap.put(config.get("key").toString(), consumerDatasource); //获取数据源的key,以便通过该key可以定位到数据源
        }
        GenericBeanDefinition define = new GenericBeanDefinition(); //bean定义类
        define.setBeanClass(MultiDataSource.class); //设置bean的类型,此处MultiDataSource是继承AbstractRoutingDataSource的实现类
        MutablePropertyValues mpv = define.getPropertyValues(); //需要注入的参数,类似spring配置文件中的<property/>
        mpv.add("defaultTargetDataSource", defaultDatasource); //添加默认数据源,避免key不存在的情况没有数据源可用
        mpv.add("targetDataSources", sourceMap); //添加其他数据源
        beanDefinitionRegistry.registerBeanDefinition("datasource", define); //将该bean注册为datasource,不使用springboot自动生成的datasource
    }

    /**
     * 通过字符串获取数据源class对象
     *
     * @param typeStr
     * @return
     */
    private Class<? extends DataSource> getDataSourceType(String typeStr) {
        Class<? extends DataSource> type;
        try {
            if (StringUtils.hasLength(typeStr)) { //字符串不为空则通过反射获取class对象
                type = (Class<? extends DataSource>) Class.forName(typeStr);
            } else {
                type = HikariDataSource.class;  //默认为hikariCP数据源,与springboot默认数据源保持一致
            }
            return type;
        } catch (Exception e) {
            throw new IllegalArgumentException("can not resolve class with type: " + typeStr); //无法通过反射获取class对象的情况则抛出异常,该情况一般是写错了,所以此次抛出一个runtimeexception
        }
    }

    /**
     * 绑定参数,以下三个方法都是参考DataSourceBuilder的bind方法实现的,目的是尽量保证我们自己添加的数据源构造过程与springboot保持一致
     *
     * @param result
     * @param properties
     */
    private void bind(DataSource result, Map properties) {
        ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
        Binder binder = new Binder(new ConfigurationPropertySource[]{source.withAliases(aliases)});
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));  //将参数绑定到对象
    }

    private <T extends DataSource> T bind(Class<T> clazz, Map properties) {
        ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
        Binder binder = new Binder(new ConfigurationPropertySource[]{source.withAliases(aliases)});
        return binder.bind(ConfigurationPropertyName.EMPTY, Bindable.of(clazz)).get(); //通过类型绑定参数并获得实例对象
    }

    /**
     * @param clazz
     * @param sourcePath 参数路径,对应配置文件中的值,如: spring.datasource
     * @param <T>
     * @return
     */
    private <T extends DataSource> T bind(Class<T> clazz, String sourcePath) {
        Map properties = binder.bind(sourcePath, Map.class).get();
        return bind(clazz, properties);
    }

    /**
     * EnvironmentAware接口的实现方法,通过aware的方式注入,此处是environment对象
     *
     * @param environment
     */
    @Override
    public void setEnvironment(Environment environment) {
        this.evn = environment;
        binder = Binder.get(evn); //绑定配置器
    }
}

二、编辑application.yml**

这边放起自己的布置文件application.yml :

server.port=8080
#数据源配置(默认)
#useSSL=false MySQL在高版本需要指明是否进行SSL连接(不加第一次连接数据库会有警告信息)
spring.datasource.driver=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
#ds1,ds2 其他两个数据源
slave.datasource.names=ds1,ds2
#ds1
slave.datasource.ds1.driver=com.mysql.jdbc.Driver
slave.datasource.ds1.url=jdbc:mysql://localhost:3306/test1?useSSL=false
slave.datasource.ds1.username=root
slave.datasource.ds1.password=123456
#ds2
slave.datasource.ds2.driver=com.mysql.jdbc.Driver
slave.datasource.ds2.url=jdbc:mysql://localhost:3306/test2?useSSL=false
slave.datasource.ds2.username=root
slave.datasource.ds2.password=123456
#mapper.xml文件
mybatis.mapper-locations=classpath:mapper/*.xml
#实体类包
mybatis.type-aliases-package=datasource.springboot_datasource.entity
spring:
  datasource:
    password: 123456
    url: jdbc:mysql://127.0.0.1:3306/graduation_project?useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver
    username: ivan
    openMulti: true
    type: com.zaxxer.hikari.HikariDataSource
    idle-timeout: 30000
    multi:
    - key: default1
      password: 123456
      url: jdbc:mysql://127.0.0.1:3306/graduation_project?useUnicode=true&characterEncoding=UTF-8
      idle-timeout: 20000
      driver-class-name: com.mysql.jdbc.Driver
      username: ivan
      type: com.alibaba.druid.pool.DruidDataSource
    - key: gd
      password: 123456
      url: jdbc:mysql://gd.badtheway.xin:****/graduation_project?useUnicode=true&characterEncoding=UTF-8
      driver-class-name: com.mysql.jdbc.Driver
      username: ivan
mybatis:
  config-location: classpath:mapper/configure.xml
  mapper-locations: classpath:mapper/*Mapper.xml

三、DataSource工具类

当即边表达一下,spring.datasource路径下之部署即默认数据源的部署,我是为个人美感和便于,所以在配置多数据源时行使spring.datasource.multi这些路,倘使要改变的言语修改MultiDataSourceRegister.java里面相应的价值就是可了。

动态切换类

终极别忘了当@SpringBootApplication加上@Import(MultiDataSourceRegister.class)

package com.chaoqi.springboot_datasource.config;

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

/**
 * @Author caiChaoqi
 * @Date 2018-06-23
 * @Description 动态数据源
 * AbstractRoutingDataSource(每执行一次数据库,动态获取DataSource)
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }
}

 

 

下边是本身好行使的一些断面配置,通过@MultiDataSource$DataSource声明标记需要切换数据源的类似,能够由此方法体参数->方法注解->类讲明实现切换数据源。供我们参考:

动态数据源上下文管理

package com.chaoqi.springboot_datasource.config;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author caiChaoqi
 * @Date 2018-06-23
 * @Description 动态数据源上下文管理
 */
public class DynamicDataSourceContextHolder {

    private Logger logger = Logger.getLogger(DynamicDataSourceContextHolder.class);
    //存放当前线程使用的数据源类型信息
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    //存放数据源id
    public static List<String> dataSourceIds = new ArrayList<String>();

    //设置数据源
    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }

    //获取数据源
    public static String getDataSourceType() {
        return contextHolder.get();
    }

    //清除数据源
    public static void clearDataSourceType() {
        contextHolder.remove();
    }

    //判断当前数据源是否存在
    public static boolean isContainsDataSource(String dataSourceId) {
        return dataSourceIds.contains(dataSourceId);
    }
}

MultiDataSource.java:

 

package top.ivan.demo.springboot.mapper;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;
import java.util.Set;

public class MultiDataSource extends AbstractRoutingDataSource {

    private final static ThreadLocal<String> DATA_SOURCE_KEY = new ThreadLocal<>(); //保存当前线程的数据源对应的key

    private Set<Object> keySet;  //所有数据源的key集合

    private static void switchSource(String key) {
        DATA_SOURCE_KEY.set(key); //切换当先线程的key
    }

    private static void clear() {
        DATA_SOURCE_KEY.remove(); //移除key值
    }

    public static Object execute(String ds, Run run) throws Throwable {
        switchSource(ds);
        try {
            return run.run();
        } finally {
            clear();
        }
    }

    //AbstractRoutingDataSource抽象类实现方法,即获取当前线程数据源的key
    @Override
    protected Object determineCurrentLookupKey() {
        String key = DATA_SOURCE_KEY.get();
        if (!keySet.contains(key)) {
            logger.info(String.format("can not found datasource by key: '%s',this session may use default datasource", key));
        }
        return key;
    }

    /**
     * 在获取key的集合,目的只是为了添加一些告警日志
     */
    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        try {
            Field sourceMapField = AbstractRoutingDataSource.class.getDeclaredField("resolvedDataSources");
            sourceMapField.setAccessible(true);
            Map<Object, javax.sql.DataSource> sourceMap = (Map<Object, javax.sql.DataSource>) sourceMapField.get(this);
            this.keySet = sourceMap.keySet();
            sourceMapField.setAccessible(false);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    public interface Run {
        Object run() throws Throwable;
    }

    /**
     * 用于获取AOP切点及数据源key的注解
     */
    @Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface DataSource {
        String value() default ""; //该值即key值
    }

    /**
     * 声明切面
     */
    @Component
    @Aspect
    @Order(-10)  //使该切面在事务之前执行
    public static class DataSourceSwitchInterceptor {

        /**
         * 扫描所有含有@MultiDataSource$DataSource注解的类
         */
        @Pointcut("@within(top.ivan.demo.springboot.mapper.MultiDataSource.DataSource)")
        public void switchDataSource() {
        }

        /**
         * 使用around方式监控
         * @param point
         * @return
         * @throws Throwable
         */
        @Around("switchDataSource()")
        public Object switchByMethod(ProceedingJoinPoint point) throws Throwable {
            Method method = getMethodByPoint(point); //获取执行方法
            Parameter[] params = method.getParameters(); //获取执行参数
            Parameter parameter;
            String source = null;
            boolean isDynamic = false;
            for (int i = params.length - 1; i >= 0; i--) { //扫描是否有参数带有@DataSource注解
                parameter = params[i];
                if (parameter.getAnnotation(DataSource.class) != null && point.getArgs()[i] instanceof String) {
                    source = (String) point.getArgs()[i]; //key值即该参数的值,要求该参数必须为String类型
                    isDynamic = true;
                    break;
                }
            }
            if (!isDynamic) { //不存在参数带有Datasource注解
                DataSource dataSource = method.getAnnotation(DataSource.class); //获取方法的@DataSource注解
                if (null == dataSource || !StringUtils.hasLength(dataSource.value())) { //方法不含有注解
                    dataSource = method.getDeclaringClass().getAnnotation(DataSource.class); //获取类级别的@DataSource注解
                }
                if (null != dataSource) {
                    source = dataSource.value(); //设置key值
                }
            }
            return persistBySource(source, point); //继续执行该方法
        }


        private Object persistBySource(String source, ProceedingJoinPoint point) throws Throwable {
            try {
                switchSource(source); //切换数据源
                return point.proceed(); //执行
            } finally {
                clear(); //清空key值
            }
        }

        private Method getMethodByPoint(ProceedingJoinPoint point) {
            MethodSignature methodSignature = (MethodSignature) point.getSignature();
            return methodSignature.getMethod();
        }
    }

}
初始化数据源和提供了执行动态切换数据源的工具类

package com.chaoqi.springboot_datasource.config;

import org.apache.log4j.Logger;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

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

/**
 * @Author caiChaoqi
 * @Date 2018-06-23
 * @Description 注册动态数据源
 * 初始化数据源和提供了执行动态切换数据源的工具类
 * EnvironmentAware(获取配置文件配置的属性值)
 */

public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private Logger logger = Logger.getLogger(DynamicDataSourceRegister.class);

    //指定默认数据源(springboot2.0默认数据源是hikari如何想使用其他数据源可以自己配置)
    private static final String DATASOURCE_TYPE_DEFAULT = "com.zaxxer.hikari.HikariDataSource";
    //默认数据源
    private DataSource defaultDataSource;
    //用户自定义数据源
    private Map<String, DataSource> slaveDataSources = new HashMap<>();

    @Override
    public void setEnvironment(Environment environment) {
        initDefaultDataSource(environment);
        initslaveDataSources(environment);
    }

    private void initDefaultDataSource(Environment env) {
        // 读取主数据源
        Map<String, Object> dsMap = new HashMap<>();
        dsMap.put("driver", env.getProperty("spring.datasource.driver"));
        dsMap.put("url", env.getProperty("spring.datasource.url"));
        dsMap.put("username", env.getProperty("spring.datasource.username"));
        dsMap.put("password", env.getProperty("spring.datasource.password"));
        defaultDataSource = buildDataSource(dsMap);
    }


    private void initslaveDataSources(Environment env) {
        // 读取配置文件获取更多数据源
        String dsPrefixs = env.getProperty("slave.datasource.names");
        for (String dsPrefix : dsPrefixs.split(",")) {
            // 多个数据源
            Map<String, Object> dsMap = new HashMap<>();
            dsMap.put("driver", env.getProperty("slave.datasource." + dsPrefix + ".driver"));
            dsMap.put("url", env.getProperty("slave.datasource." + dsPrefix + ".url"));
            dsMap.put("username", env.getProperty("slave.datasource." + dsPrefix + ".username"));
            dsMap.put("password", env.getProperty("slave.datasource." + dsPrefix + ".password"));
            DataSource ds = buildDataSource(dsMap);
            slaveDataSources.put(dsPrefix, ds);
        }
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        //添加默认数据源
        targetDataSources.put("dataSource", this.defaultDataSource);
        DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
        //添加其他数据源
        targetDataSources.putAll(slaveDataSources);
        for (String key : slaveDataSources.keySet()) {
            DynamicDataSourceContextHolder.dataSourceIds.add(key);
        }

        //创建DynamicDataSource
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(DynamicDataSource.class);
        beanDefinition.setSynthetic(true);
        MutablePropertyValues mpv = beanDefinition.getPropertyValues();
        mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
        mpv.addPropertyValue("targetDataSources", targetDataSources);
        //注册 - BeanDefinitionRegistry
        beanDefinitionRegistry.registerBeanDefinition("dataSource", beanDefinition);

        logger.info("Dynamic DataSource Registry");
    }

    public DataSource buildDataSource(Map<String, Object> dataSourceMap) {
        try {
            Object type = dataSourceMap.get("type");
            if (type == null) {
                type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource
            }
            Class<? extends DataSource> dataSourceType;
            dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);
            String driverClassName = dataSourceMap.get("driver").toString();
            String url = dataSourceMap.get("url").toString();
            String username = dataSourceMap.get("username").toString();
            String password = dataSourceMap.get("password").toString();
            // 自定义DataSource配置
            DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url)
                    .username(username).password(password).type(dataSourceType);
            return factory.build();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

示例:

 

package top.ivan.demo.springboot.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import top.ivan.demo.springboot.pojo.ProductPreview;

import java.util.List;

@Mapper
@MultiDataSource.DataSource("ds1")
public interface PreviewMapper {

    //使用ds的值作为key
    List<ProductPreview> getList(@Param("start") int start, @Param("count") int count, @MultiDataSource.DataSource String ds);

    //使用“ds2”作为key
    @MultiDataSource.DataSource("ds2")
    List<ProductPreview> getList2(@Param("start") int start, @Param("count") int count);

    //使用“ds1”作为key
    List<ProductPreview> getList3(@Param("start") int start, @Param("count") int count);

}

自定义声明

眼看几上恰好沾springboot,还处在小白的状态,倘使有啊问题之说话欢迎我们指教

package com.chaoqi.springboot_datasource.config;

import java.lang.annotation.*;

/**
 * @Author caiChaoqi
 * @Date 2018-06-23
 * @Description 作用于类、接口或者方法上
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {

    String name();
}

动态数据源通知

package com.chaoqi.springboot_datasource.config;

import org.apache.log4j.Logger;
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.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Author caiChaoqi
 * @Description 动态数据源通知
 * @Date 2018-06-23
 */
@Aspect
@Order(-1)//保证在@Transactional之前执行
@Component
public class DynamicDattaSourceAspect {

    private Logger logger = Logger.getLogger(DynamicDattaSourceAspect.class);

    //改变数据源
    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        String dbid = targetDataSource.name();

        if (!DynamicDataSourceContextHolder.isContainsDataSource(dbid)) {
            //joinPoint.getSignature() :获取连接点的方法签名对象
            logger.error("数据源 " + dbid + " 不存在使用默认的数据源 -> " + joinPoint.getSignature());
        } else {
            logger.debug("使用数据源:" + dbid);
            DynamicDataSourceContextHolder.setDataSourceType(dbid);
        }
    }

    @After("@annotation(targetDataSource)")
    public void clearDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        logger.debug("清除数据源 " + targetDataSource.name() + " !");
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}

主旨代码以全方位示,源码下载地址:https://github.com/caicahoqi/ChaoqiIsPrivateLibrary 假如以档次搭建着相见题目可以当评论区留言,博主看到第一时间会与回复,谢谢

蹭源码文件: https://files.cnblogs.com/files/badtheway/springboot.zip

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图