zoukankan      html  css  js  c++  java
  • Springbooot +Mybaties 配置数据库多数据源

    前言

      在实际项目中,我们可能会碰到在一个项目中会访问多个数据库的情况。针对这种情况,我们就需要配置动态的数据源了。一般按照以下步骤即可

    一、在启动类上添加注解

    二、在application.properties文件中

    #默认数据源

    spring.datasource.driver-class-name= com.mysql.jdbc.Driver
    spring.datasource.url = jdbc:mysql://127.0.0.1:3306/tianxi_mall?useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&allowMultiQueries=true

    spring.datasource.username = root
    spring.datasource.password =


    #其他数据源.sqlserver
    custom.datasource.names = ds1
    custom.datasource.ds1.driver-class-name = com.mysql.jdbc.Driver
    custom.datasource.ds1.url = jdbc:mysql://192.168.2.2:3306/wechat?useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&allowMultiQueries=true
    custom.datasource.ds1.username = root
    custom.datasource.ds1.password =

    注:假如其他的数据源不是mysql,请自行百度其他数据的连接驱动

    三、配置

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

    /**
    * AbstractRoutingDataSource获取数据源之前会先调用determineCurrentLookupKey方法查找当前的lookupKey,这个lookupKey就是数据源标识。
    因此通过重写这个查找数据源标识的方法就可以让spring切换到指定的数据源了
    * @author mayn
    *
    */
    public class DynamicDataSource extends AbstractRoutingDataSource{
    protected Object determineCurrentLookupKey() {
    //从自定义位置获取数据源标识
    return DynamicDataSourceContextHolder.getDataSourceType();
    }
    }

    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;
    /**
    * // 保证该AOP在@Transactional之前执行
    * @author mayn
    *
    */
    @Component
    @Aspect
    @Order(-1)
    public class DynamicDataSourceAspect {
    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
    String dsId = ds.name();
    if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
    logger.error("数据源[{}]不存在,使用默认数据源 > {}", ds.name(), point.getSignature());
    } else {
    logger.debug("Use DataSource : {} > {}", ds.name(), point.getSignature());
    DynamicDataSourceContextHolder.setDataSourceType(ds.name());
    }
    }

    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
    logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature());
    DynamicDataSourceContextHolder.clearDataSourceType();
    }
    }

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

    /**
    * 用于持有当前线程中使用的数据源标识
    * @author mayn
    *
    */
    public class DynamicDataSourceContextHolder {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    public static List<String> dataSourceIds = new ArrayList<>();

    public static void setDataSourceType(String dataSourceType) {
    contextHolder.set(dataSourceType);
    }

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

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

    /** * 判断指定DataSrouce当前是否存在 * */
    public static boolean containsDataSource(String dataSourceId){
    return dataSourceIds.contains(dataSourceId);
    }
    }

    import java.util.HashMap;
    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.PropertyValues;
    import org.springframework.beans.factory.support.BeanDefinitionRegistry;
    import org.springframework.beans.factory.support.GenericBeanDefinition;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
    import org.springframework.boot.bind.RelaxedDataBinder;
    import org.springframework.boot.bind.RelaxedPropertyResolver;
    import org.springframework.context.EnvironmentAware;
    import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
    import org.springframework.core.convert.ConversionService;
    import org.springframework.core.convert.support.DefaultConversionService;
    import org.springframework.core.env.Environment;
    import org.springframework.core.type.AnnotationMetadata;


    public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);

    private ConversionService conversionService = new DefaultConversionService();
    private PropertyValues dataSourcePropertyValues;

    // 如配置文件中未指定数据源类型,使用该默认值
    private static final Object DATASOURCE_TYPE_DEFAULT = "org.apache.tomcat.jdbc.pool.DataSource";
    // private static final Object DATASOURCE_TYPE_DEFAULT =
    // "com.zaxxer.hikari.HikariDataSource";

    // 数据源
    private DataSource defaultDataSource;
    private Map<String, DataSource> customDataSources = new HashMap<>();

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
    // 将主数据源添加到更多数据源中
    targetDataSources.put("dataSource", defaultDataSource);
    DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
    // 添加更多数据源
    targetDataSources.putAll(customDataSources);
    for (String key : customDataSources.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);
    registry.registerBeanDefinition("dataSource", beanDefinition);

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

    /** * 创建DataSource * * @param type * @param driverClassName * @param url * @param username * @param password * @return * @author SHANHY * @create 2016年1月24日 */
    @SuppressWarnings("unchecked")
    public DataSource buildDataSource(Map<String, Object> dsMap) {
    try {
    Object type = dsMap.get("type");
    if (type == null)
    type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource

    Class<? extends DataSource> dataSourceType;
    dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);

    String driverClassName = dsMap.get("driver-class-name").toString();
    String url = dsMap.get("url").toString();
    String username = dsMap.get("username").toString();
    String password = dsMap.get("password").toString();

    DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url)
    .username(username).password(password).type(dataSourceType);
    return factory.build();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    return null;
    }

    /** * 加载多数据源配置 */
    public void setEnvironment(Environment env) {
    initDefaultDataSource(env);
    initCustomDataSources(env);
    }

    /** * 初始化主数据源 * * @author SHANHY * @create 2016年1月24日 */
    private void initDefaultDataSource(Environment env) {
    // 读取主数据源
    RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
    Map<String, Object> dsMap = new HashMap<>();
    dsMap.put("type", propertyResolver.getProperty("type"));
    dsMap.put("driver-class-name", propertyResolver.getProperty("driver-class-name"));
    dsMap.put("url", propertyResolver.getProperty("url"));
    dsMap.put("username", propertyResolver.getProperty("username"));
    dsMap.put("password", propertyResolver.getProperty("password"));

    defaultDataSource = buildDataSource(dsMap);

    dataBinder(defaultDataSource, env);
    }

    /** * 为DataSource绑定更多数据 * * @param dataSource * @param env * @author SHANHY * @create 2016年1月25日 */
    private void dataBinder(DataSource dataSource, Environment env){
    RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
    //dataBinder.setValidator(new LocalValidatorFactory().run(this.applicationContext));
    dataBinder.setConversionService(conversionService);
    dataBinder.setIgnoreNestedProperties(false);//false
    dataBinder.setIgnoreInvalidFields(false);//false
    dataBinder.setIgnoreUnknownFields(true);//true
    if(dataSourcePropertyValues == null){
    Map<String, Object> rpr = new RelaxedPropertyResolver(env, "spring.datasource").getSubProperties(".");
    Map<String, Object> values = new HashMap<>(rpr);
    // 排除已经设置的属性
    values.remove("type");
    values.remove("driver-class-name");
    values.remove("url");
    values.remove("username");
    values.remove("password");
    dataSourcePropertyValues = new MutablePropertyValues(values);
    }
    dataBinder.bind(dataSourcePropertyValues);
    }

    /** * 初始化更多数据源 * * @author SHANHY * @create 2016年1月24日 */
    private void initCustomDataSources(Environment env) {
    // 读取配置文件获取更多数据源,也可以通过defaultDataSource读取数据库获取更多数据源
    RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "custom.datasource.");
    String dsPrefixs = propertyResolver.getProperty("names");
    for (String dsPrefix : dsPrefixs.split(",")) {// 多个数据源
    Map<String, Object> dsMap = propertyResolver.getSubProperties(dsPrefix + ".");
    DataSource ds = buildDataSource(dsMap);
    customDataSources.put(dsPrefix, ds);
    dataBinder(ds, env);
    }
    }
    }

    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;

    /**
    * 自定义注解
    * @author mayn
    *
    */
    @Target({ElementType.METHOD, ElementType.TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface TargetDataSource {
    String name();
    }

    四、配置完成后,只需在要切换数据源的映射接口上添加注解@TargetDataSource(name="ds1") 即可。注意,ds1是自定义的,对应了配置application.properties中的ds1,如下

    /**
    * 切换数据源查询
    */
    @TargetDataSource(name="ds1")
    public List<CardInfoResponse> cardInfo(String card_id) {
    return cardMapper.cardInfo(card_id);
    }

    五、至此,完成,亲测有效。假如需要拓展更多的数据源,则相应继续往下配置即可。

  • 相关阅读:
    [置顶] cAdvisor、InfluxDB、Grafana搭建Docker1.12性能监控平台
    15 个 Docker 技巧和提示
    Docker资源管理探秘:Docker背后的内核Cgroups机制
    SVN通过域名连不上服务器地址(svn: E175002: OPTIONS request failed on '/svn/yx-SVN-Server' Connection refused: connect)
    图片点击放大功能
    jquery-选择checkbox的多种策略
    HTML-input标签需设置的属性
    MyBatis-配置缓存
    SpringMVC redirect乱码问题
    Mysql-左连接查询条件失效的解决办法
  • 原文地址:https://www.cnblogs.com/memoa/p/10025548.html
Copyright © 2011-2022 走看看