springboot+mybatis多数据源配置

こ雲淡風輕ζ 提交于 2021-02-05 06:25:19

1.配置文件配置两个数据源。application.properties

## 端口
server.port=8080

# 数据库访问配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.first-url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull&useSSL=false
spring.datasource.first-username=root
spring.datasource.first-password=zyh123

spring.datasource.historyUrl=jdbc:mysql://localhost:3306/test_history?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull&useSSL=false
spring.datasource.historyUsername=root
spring.datasource.historyPassword=zyh123



# 下面为连接池的补充设置,应用到上面所有数据源中
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.druid.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.druid.filter.stat.enabled=true

2.实现两个config,

DataSourceConfiguration和
HistoryDataSourceConfiguration,配置类需要指定数据源,以及该数据源对应的dao,还有mapper文件路径
@Configuration
@MapperScan(basePackages = {"com.example.demo.controller","com.example.demo.dao"}, sqlSessionTemplateRef  = "sqlSessionTemplate")
public class DataSourceConfiguration {
    public final static org.slf4j.Logger logger = LoggerFactory.getLogger(DataSourceConfiguration.class);
    
    @Value("${spring.datasource.first-url}")
    private String url;
    
    @Value("${spring.datasource.first-username}")
    private String username;
    
    @Value("${spring.datasource.first-password}")
    private String password;
    
    @Value("${spring.datasource.historyUrl}")
    private String historyUrl;
    
    @Value("${spring.datasource.historyUsername}")
    private String historyUsername;
    
    @Value("${spring.datasource.historyPassword}")
    private String historyPassword;
    
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    
    @Value("${spring.datasource.druid.initialSize}")
    private int initialSize;
    
    @Value("${spring.datasource.druid.minIdle}")
    private int minIdle;
    
    @Value("${spring.datasource.druid.maxActive}")
    private int maxActive;
    
    @Value("${spring.datasource.druid.maxWait}")
    private int maxWait;
    
    @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    
    @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    
    @Value("${spring.datasource.druid.validationQuery}")
    private String validationQuery;
    
    @Value("${spring.datasource.druid.testWhileIdle}")
    private boolean testWhileIdle;
    
    @Value("${spring.datasource.druid.testOnBorrow}")
    private boolean testOnBorrow;
    
    @Value("${spring.datasource.druid.testOnReturn}")
    private boolean testOnReturn;
    
    @Bean(name = "dataSource") 
    @Primary
    public DataSource dataSource(){  
        logger.info("初始化数据库连接池");
        DruidDataSource datasource = new DruidDataSource();  
        datasource.setUrl(url);  
        datasource.setUsername(username);  
        datasource.setPassword(password);  
        datasource.setDriverClassName(driverClassName);  
  
        //configuration  
        datasource.setInitialSize(initialSize);  
        datasource.setMinIdle(minIdle);  
        datasource.setMaxActive(maxActive);  
        datasource.setMaxWait(maxWait);  
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
        datasource.setValidationQuery(validationQuery);  
        datasource.setTestWhileIdle(testWhileIdle);  
        datasource.setTestOnBorrow(testOnReturn);  
        datasource.setTestOnReturn(testOnReturn);  
        logger.info("初始化数据库连接池完成");
        return datasource;  
    } 

    @Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource")DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    
    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        bean.setTypeAliasesPackage("com.example.demo.model");
        return bean.getObject();
    }
    
    @Bean(name = "sqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
@Configuration
@MapperScan(basePackages = "com.example.demo.historyDao", sqlSessionTemplateRef  = "historySqlSessionTemplate")
public class HistoryDataSourceConfiguration {
    public final static org.slf4j.Logger logger = LoggerFactory.getLogger(HistoryDataSourceConfiguration.class);
    
    @Value("${spring.datasource.first-url}")
    private String url;
    
    @Value("${spring.datasource.first-username}")
    private String username;
    
    @Value("${spring.datasource.first-password}")
    private String password;
    
    @Value("${spring.datasource.historyUrl}")
    private String historyUrl;
    
    @Value("${spring.datasource.historyUsername}")
    private String historyUsername;
    
    @Value("${spring.datasource.historyPassword}")
    private String historyPassword;
    
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    
    @Value("${spring.datasource.druid.initialSize}")
    private int initialSize;
    
    @Value("${spring.datasource.druid.minIdle}")
    private int minIdle;
    
    @Value("${spring.datasource.druid.maxActive}")
    private int maxActive;
    
    @Value("${spring.datasource.druid.maxWait}")
    private int maxWait;
    
    @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    
    @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    
    @Value("${spring.datasource.druid.validationQuery}")
    private String validationQuery;
    
    @Value("${spring.datasource.druid.testWhileIdle}")
    private boolean testWhileIdle;
    
    @Value("${spring.datasource.druid.testOnBorrow}")
    private boolean testOnBorrow;
    
    @Value("${spring.datasource.druid.testOnReturn}")
    private boolean testOnReturn;
    
    @Bean(name = "historyDataSource")     
    public DataSource historyDataSource(){  
        logger.info("初始化历史库数据库连接池");
        DruidDataSource datasource = new DruidDataSource();  
        datasource.setUrl(historyUrl);  
        datasource.setUsername(historyUsername);  
        datasource.setPassword(historyPassword);  
        datasource.setDriverClassName(driverClassName);  
  
        //configuration  
        datasource.setInitialSize(initialSize);  
        datasource.setMinIdle(minIdle);  
        datasource.setMaxActive(maxActive);  
        datasource.setMaxWait(maxWait);  
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
        datasource.setValidationQuery(validationQuery);  
        datasource.setTestWhileIdle(testWhileIdle);  
        datasource.setTestOnBorrow(testOnReturn);  
        datasource.setTestOnReturn(testOnReturn);  
        logger.info("初始化历史库数据库连接池完成");
        return datasource;  
    } 

    @Bean(name = "historyTransactionManager")
    public DataSourceTransactionManager historyTransactionManager(@Qualifier("historyDataSource")DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    
    
    @Bean(name = "historySqlSessionFactory")
    public SqlSessionFactory historySqlSessionFactory(@Qualifier("historyDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        bean.setTypeAliasesPackage("com.example.demo.model");
        return bean.getObject();
    }
    
    @Bean(name = "historySqlSessionTemplate")
    public SqlSessionTemplate historySqlSessionTemplate(@Qualifier("historySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

这样多数据源配置就完成了。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!