spring boot配置多个数据源(oracle)

开始吧

在自己的项目下新建一个包,新建文件依次复制粘贴下列代码

1

package ***********.datasource;
 
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
 
import com.zxht.smart.environment.annotation.DataSource;
 
 
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {
 
	
	private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
 
    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, DataSource ds) throws Throwable {
        String dsId = ds.value();
        if (DynamicDataSourceContextHolder.dataSourceIds.contains(dsId)) {
            logger.debug("Use DataSource :{} >", dsId, point.getSignature());
            DynamicDataSourceContextHolder.setDataSourceRouterKey(dsId);
        } else {
            logger.info("数据源[{}]不存在,使用默认数据源 >{}", dsId, point.getSignature());
            
        }
    }
 
    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, DataSource ds) {
        logger.debug("Revert DataSource : " + ds.value() + " > " + point.getSignature());
        DynamicDataSourceContextHolder.removeDataSourceRouterKey();
 
    }
}

2

import java.util.ArrayList;
import java.util.List;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class DynamicDataSourceContextHolder {
 
	
	private static Logger logger = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);
 
    /**
     * 存储已经注册的数据源的key
     */
    public static List dataSourceIds = new ArrayList<>();
 
    /**
     * 线程级别的私有变量
     */
    private static final ThreadLocal HOLDER = new ThreadLocal<>();
 
    public static String getDataSourceRouterKey () {
        return HOLDER.get();
    }
 
    public static void setDataSourceRouterKey (String dataSourceRouterKey) {
        logger.info("切换至{}数据源", dataSourceRouterKey);
        HOLDER.set(dataSourceRouterKey);
    }
 
    /**
     * 设置数据源之前一定要先移除
     */
    public static void removeDataSourceRouterKey () {
        HOLDER.remove();
    }
 
    /**
     * 判断指定DataSrouce当前是否存在
     *
     * @param dataSourceId
     * @return
     */
    public static boolean containsDataSource(String dataSourceId){
        return dataSourceIds.contains(dataSourceId);
    }
}

3

import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.sql.DataSource;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 com.zaxxer.hikari.HikariDataSource;
 
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware{
	
	private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);
 
 
    /**
     * 配置上下文(也可以理解为配置文件的获取工具)
     */
    private Environment evn;
 
    /**
     * 别名
     */
    private final static ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
 
    /**
     * 由于部分数据源配置不同,所以在此处添加别名,避免切换数据源出现某些参数无法注入的情况
     */
    static {
        aliases.addAliases("url", new String[]{"jdbc-url"});
        aliases.addAliases("username", new String[]{"user"});
    }
 
    /**
     * 存储我们注册的数据源
     */
    private Map customDataSources = new HashMap();
 
    /**
     * 参数绑定工具 springboot2.0新推出
     */
    private Binder binder;
 
    /**
     * ImportBeanDefinitionRegistrar接口的实现方法,通过该方法可以按照自己的方式注册bean
     *
     * @param annotationMetadata
     * @param beanDefinitionRegistry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        // 获取所有数据源配置
        Map config, defauleDataSourceProperties;
        defauleDataSourceProperties = binder.bind("spring.datasource.master", Map.class).get();
        // 获取数据源类型
        String typeStr = evn.getProperty("spring.datasource.master.type");
        // 获取数据源类型
        Class clazz = getDataSourceType(typeStr);
        // 绑定默认数据源参数 也就是主数据源
        DataSource consumerDatasource, defaultDatasource = bind(clazz, defauleDataSourceProperties);
        DynamicDataSourceContextHolder.dataSourceIds.add("master");
        logger.info("注册默认数据源成功");
        // 获取其他数据源配置
        List configs = binder.bind("spring.datasource.cluster", Bindable.listOf(Map.class)).get();
        // 遍历从数据源
        for (int i = 0; i < configs.size(); i++) {
            config = configs.get(i);
            clazz = getDataSourceType((String) config.get("type"));
            defauleDataSourceProperties = config;
            // 绑定参数
            consumerDatasource = bind(clazz, defauleDataSourceProperties);
            // 获取数据源的key,以便通过该key可以定位到数据源
            String key = config.get("key").toString();
            customDataSources.put(key, consumerDatasource);
            // 数据源上下文,用于管理数据源与记录已经注册的数据源key
            DynamicDataSourceContextHolder.dataSourceIds.add(key);
            logger.info("注册数据源{}成功", key);
        }
        // bean定义类
        GenericBeanDefinition define = new GenericBeanDefinition();
        // 设置bean的类型,此处DynamicRoutingDataSource是继承AbstractRoutingDataSource的实现类
        define.setBeanClass(DynamicRoutingDataSource.class);
        // 需要注入的参数
        MutablePropertyValues mpv = define.getPropertyValues();
        // 添加默认数据源,避免key不存在的情况没有数据源可用
        mpv.add("defaultTargetDataSource", defaultDatasource);
        // 添加其他数据源
        mpv.add("targetDataSources", customDataSources);
        // 将该bean注册为datasource,不使用springboot自动生成的datasource
        beanDefinitionRegistry.registerBeanDefinition("datasource", define);
        logger.info("注册数据源成功,一共注册{}个数据源", customDataSources.keySet().size() + 1);
    }
 
    /**
     * 通过字符串获取数据源class对象
     *
     * @param typeStr
     * @return
     */
    private Class getDataSourceType(String typeStr) {
        Class type;
        try {
            if (StringUtils.hasLength(typeStr)) {
                // 字符串不为空则通过反射获取class对象
                type = (Class) Class.forName(typeStr);
            } else {
                // 默认为hikariCP数据源,与springboot默认数据源保持一致
                type = HikariDataSource.class;
            }
            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 bind(Class 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 
     * @return
     */
    private  T bind(Class 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) {
        logger.info("开始注册数据源");
        this.evn = environment;
        // 绑定配置器
        binder = Binder.get(evn);
    }
}

4

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
 
public class DynamicRoutingDataSource extends AbstractRoutingDataSource  {
 
	
	private static Logger logger = LoggerFactory.getLogger(DynamicRoutingDataSource.class);
 
    @Override
    protected Object determineCurrentLookupKey() {
        String dataSourceName = DynamicDataSourceContextHolder.getDataSourceRouterKey();
        logger.info("当前数据源是:{}", dataSourceName);
        return DynamicDataSourceContextHolder.getDataSourceRouterKey();
    }
}

5

#配置数据源

spring:
  datasource:
    master: 
      url: xxxx1
      username: xxxx1
      password: xxxx1
      driver-class-name: oracle.jdbc.OracleDriver
    cluster: 
    - key: economy
      url: xxxx2
      username: xxxx2
      password: xxxx2
      driver-class-name: oracle.jdbc.OracleDriver

6

   import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
/**
 * 切换数据注解 可以用于类或者方法级别 方法级别优先级 > 类级别
 */
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
	String value() default "master"; //该值即key值
}

注解默认值是master ,也就是主数据源

7在自己需要切换的dao层上加上注解即可

import java.util.List;
 
import org.apache.ibatis.annotations.Mapper;
 
import com.zxht.smart.environment.annotation.DataSource;
import com.zxht.smart.environment.entity.YkljSanitationResult;
 
@Mapper
public interface YkljSanitationResultDao {
 
	@DataSource("economy")
	List xxxxxxResult();
}

8在启动类上别忘了加import注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableScheduling;
 
import com.zxht.smart.environment.datasource.DynamicDataSourceRegister;
 
 
@SpringBootApplication
@EnableScheduling
**@Import({DynamicDataSourceRegister.class})** // 注册动态多数据源
public class SmartEnvironmentSystemApplication {
 
	public static void main(String[] args) {
		SpringApplication.run(SmartEnvironmentSystemApplication.class, args);
	}
 
}

9
在配置文件中加入下面的依赖

 
        
            junit
            junit
        
        
            org.aspectj
            aspectjweaver
            1.9.4
        
        
            org.aspectj
            aspectjrt
            1.8.9
        
        
            org.springframework
            spring-jdbc
            5.1.9.RELEASE
        
        
            com.zaxxer
            HikariCP
            3.2.0
        

注意细节!!!括号,符号之类的,就此运行项目,进行测试,基本就0k了

你可能感兴趣的:(java工具类,java,后端,数据库)