springboot 整合多数据源手动切换

配置文件如下

server.port = 11000
#热部署
spring.devtools.restart.enabled=true
spring.aop.auto=true


# DB Configuration
#指定数据1库驱动
spring.datasource.db1.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库1jdbc连接url地址,serverTimezone设置数据库时区东八区
spring.datasource.db1.jdbc-url=jdbc:mysql://127.0.0.1:3306/redis?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2b8
#数据库1账号
spring.datasource.db1.username=root
spring.datasource.db1.password=123456

#指定数据库2驱动
spring.datasource.db2.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库2jdbc连接url地址,serverTimezone设置数据库时区东八区
spring.datasource.db2.jdbc-url=jdbc:mysql://127.0.0.1:3306/test?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2b8
#数据库2账号
spring.datasource.db2.username=root
spring.datasource.db2.password=123456


mybatis.type-aliases-package = com.learn.boot.model
mybatis.mapperLocations=classpath:mapper/*/*.xml



#redis
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000

# rabbitMQ
spring.rabbitmq.host = 127.0.0.1
spring.rabbitmq.port = 5672
spring.rabbitmq.username=test
spring.rabbitmq.password=test
spring.rabbitmq.virtual-host= /test
spring.rabbitmq.listener.simple.acknowledge-mode = manual
spring.rabbitmq.publisher-confirm-type=simple
spring.rabbitmq.publisher-returns-type=true

spring.jackson.default-property-inclusion = non_null
#这是自定义变量,表示本地开发环境
mq.env=local

接下配置DataSourceConfig

package com.learn.boot.config;


import com.learn.boot.annotion.RedisDataSource;
import com.learn.boot.annotion.TestDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author: guandezhi
 * @Date: 2019/3/14 21:06
 */
@Configuration
@MapperScan(basePackages = {"com.learn.boot.mapper.redis"}, sqlSessionTemplateRef = "redisSqlSessionTemplate")
public class RedisDataSourceConfig {

    @Primary
    @Bean(name = "redisSqlSessionFactory")
    public SqlSessionFactory chinaSqlSessionFactory(@Qualifier("redisDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/redis/*/*.xml"));
        // 扫描别名
        bean.setTypeAliasesPackage("com.learn.boot.model");
        return bean.getObject();
    }
    @Primary
    @Bean(name = "redisTransactionManager")
    public DataSourceTransactionManager chinaTransactionManager(@Qualifier("redisDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Primary
    @Bean(name = "redisSqlSessionTemplate")
    public SqlSessionTemplate chinaSqlSessionTemplate(@Qualifier("redisSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

注意
这里分库实现其实是将mapper的xml文件和mybaitis的接口文件放在不同的包下实现的

package com.learn.boot.config;


import com.learn.boot.annotion.RedisDataSource;
import com.learn.boot.annotion.TestDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author: guandezhi
 * @Date: 2019/3/14 21:06
 */
@Configuration
@MapperScan(basePackages = {"com.learn.boot.mapper.redis"}, sqlSessionTemplateRef = "redisSqlSessionTemplate")
public class RedisDataSourceConfig {

    @Primary
    @Bean(name = "redisSqlSessionFactory")
    public SqlSessionFactory chinaSqlSessionFactory(@Qualifier("redisDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/redis/*/*.xml"));
        // 扫描别名
        bean.setTypeAliasesPackage("com.learn.boot.model");
        return bean.getObject();
    }
    @Primary
    @Bean(name = "redisTransactionManager")
    public DataSourceTransactionManager chinaTransactionManager(@Qualifier("redisDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Primary
    @Bean(name = "redisSqlSessionTemplate")
    public SqlSessionTemplate chinaSqlSessionTemplate(@Qualifier("redisSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

package com.learn.boot.config;


import com.learn.boot.annotion.TestDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.omg.PortableInterceptor.Interceptor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author: guandezhi
 * @Date: 2019/3/14 21:06
 */
@Configuration
@MapperScan(basePackages = {"com.learn.boot.mapper.test"}, sqlSessionTemplateRef = "testSqlSessionTemplate")
public class TestDataSourceConfig {

    @Bean(name = "testSqlSessionFactory")
    public SqlSessionFactory chinaSqlSessionFactory(@Qualifier("testDatasource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test/*.xml"));
        // 扫描别名
        bean.setTypeAliasesPackage("com.learn.boot.model");
        return bean.getObject();
    }

    @Bean(name = "testTransactionManager")
    public DataSourceTransactionManager chinaTransactionManager(@Qualifier("testDatasource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "testSqlSessionTemplate")
    public SqlSessionTemplate chinaSqlSessionTemplate(@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

注意扫包的范围
在这里插入图片描述
最后全部加入DataSource的Bean注入

package com.learn.boot.config;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
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.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
public class DataSourceConfig {
    //数据源1
    @Bean(name = "testDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.db2") // application.properteis中对应属性的前缀
    public DataSource testDatasource() {
        return DataSourceBuilder.create().build();
    }

    //数据源2
    @Primary
    @Bean(name = "redisDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1") // application.properteis中对应属性的前缀
    public DataSource redisDataSource() {
        return DataSourceBuilder.create().build();
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值