Spring boot配置多数据源

配置第一个datasource(Primary)

 

/**
 * Druid数据源配置
 */
@Configuration
@MapperScan(basePackages = DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "sessionFactory",sqlSessionTemplateRef = "sqlSessionTemplate")
public class DataSourceConfig {
    static final String PACKAGE = "com.a.b.test1";
    private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceConfig.class);
    private static String dbUrl;

    private static String username;

    private static String password;

    private static String driverClassName;

    private static int initialSize;

    private static int minIdle;

    private static int maxActive;

    private static int maxWait;

    /**
     * 注册DruidServlet
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServletRegistrationBean() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        return servletRegistrationBean;
    }

    /**
     * 注册DruidFilter拦截
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean druidFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        Map<String, String> initParams = new HashMap<String, String>();
        //设置忽略请求
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

    /**
     * 配置DataSource
     * @return
     * @throws SQLException
     */
    @Bean(initMethod = "init",destroyMethod = "close")
    @Primary
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setUrl(dbUrl);
        druidDataSource.setFilters("stat,wall");
        druidDataSource.setInitialSize(initialSize);
        druidDataSource.setMinIdle(minIdle);
        druidDataSource.setMaxActive(maxActive);
        druidDataSource.setMaxWait(maxWait);
        druidDataSource.setUseGlobalDataSourceStat(true);
        druidDataSource.setDriverClassName(driverClassName);
        return druidDataSource;
    }

    @Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) throws SQLException {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.xxx.domain");
        //添加mybatis配置文件
        PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
//        bean.setConfigLocation(resourceResolver.getResource("classpath:mybatis/config/mybatis-config.xml"));
        try {
            bean.setMapperLocations(resourceResolver.getResources("classpath:mybatis/mapper/*.xml"));
            return bean.getObject();
        } catch (IOException e) {
            LOGGER.error("获取mapper资源出现异常",e);
            throw new RuntimeException("获取mapper资源出现异常",e);
        } catch (Exception e){
            LOGGER.error("初始化sqlSessionFactory时出现异常",e);
            throw new RuntimeException("初始化sqlSessionFactory时出现异常",e);
        }
    }

    @Bean(name = "sqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Value("${spring.datasource.url}")
    public void setDbUrl(String dbUrl) {
        DataSourceConfig.dbUrl = dbUrl;
    }

    @Value("${spring.datasource.username}")
    public void setUsername(String username) {
        DataSourceConfig.username = username;
    }

    @Value("${spring.datasource.password}")
    public void setPassword(String password) {
        DataSourceConfig.password = password;
    }

    @Value("${spring.datasource.driver-class-name}")
    public void setDriverClassName(String driverClassName) {
        DataSourceConfig.driverClassName = driverClassName;
    }

    @Value(value = "${spring.datasource.initialSize}")
    public void setInitialSize(int initialSize) {
        DataSourceConfig.initialSize = initialSize;
    }

    @Value(value = "${spring.datasource.minIdle}")
    public void setMinIdle(int minIdle) {
        DataSourceConfig.minIdle = minIdle;
    }

    @Value(value = "${spring.datasource.maxActive}")
    public void setMaxActive(int maxActive) {
        DataSourceConfig.maxActive = maxActive;
    }

    @Value(value = "${spring.datasource.maxWait}")
    public void setMaxWait(int maxWait) {
        DataSourceConfig.maxWait = maxWait;
    }
}

 配置第二个datasource

@Configuration
@MapperScan(basePackages = NewWindowsDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "nwSessionFactory",sqlSessionTemplateRef = "nwSqlSessionTemplate")
public class NewWindowsDataSourceConfig {
    static final String PACKAGE = "com.a.b.test2";   //本项目中用的是mybatis,此路径为扫描的mapper的包结构
    private static final Logger LOGGER = LoggerFactory.getLogger(NewWindowsDataSourceConfig.class);
    private static String dbUrl;

    private static String username;

    private static String password;

    private static String driverClassName;

    private static int initialSize;

    private static int minIdle;

    private static int maxActive;

    private static int maxWait;

    /**
     * 注册DruidFilter拦截
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean nwFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        Map<String, String> initParams = new HashMap<String, String>();
        //设置忽略请求
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

    /**
     * 配置DataSource
     * @return
     * @throws SQLException
     */
    @Bean(initMethod = "init",destroyMethod = "close")
    public DataSource nwDataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setUrl(dbUrl);
        druidDataSource.setFilters("stat,wall");
        druidDataSource.setInitialSize(initialSize);
        druidDataSource.setMinIdle(minIdle);
        druidDataSource.setMaxActive(maxActive);
        druidDataSource.setMaxWait(maxWait);
        druidDataSource.setUseGlobalDataSourceStat(true);
        druidDataSource.setDriverClassName(driverClassName);
        return druidDataSource;
    }

    @Bean(name = "nwTransactionManager")
    public DataSourceTransactionManager nwTransactionManager(@Qualifier("nwDataSource") DataSource nwDataSource) throws SQLException {
        return new DataSourceTransactionManager(nwDataSource());
    }

    @Bean(name = "nwSessionFactory")
    public SqlSessionFactory nwSqlSessionFactory(@Qualifier("nwDataSource") DataSource nwDataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(nwDataSource);
        bean.setTypeAliasesPackage("com.xxx.domain");
        //添加mybatis配置文件
        PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        bean.setConfigLocation(resourceResolver.getResource("classpath:mybatis/config/mybatis-config.xml"));
        try {
            bean.setMapperLocations(resourceResolver.getResources("classpath:mybatis/mapper/*.xml"));
            return bean.getObject();
        } catch (IOException e) {
            LOGGER.error("获取mapper资源出现异常",e);
            throw new RuntimeException("获取mapper资源出现异常",e);
        } catch (Exception e){
            LOGGER.error("初始化sqlSessionFactory时出现异常",e);
            throw new RuntimeException("初始化sqlSessionFactory时出现异常",e);
        }
    }

    @Bean(name = "nwSqlSessionTemplate")
    public SqlSessionTemplate nwSqlSessionTemplate(@Qualifier("nwSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Value("${nw.datasource.url}")
    public void setDbUrl(String dbUrl) {
        NewWindowsDataSourceConfig.dbUrl = dbUrl;
    }

    @Value("${nw.datasource.username}")
    public void setUsername(String username) {
        NewWindowsDataSourceConfig.username = username;
    }

    @Value("${nw.datasource.password}")
    public void setPassword(String password) {
        NewWindowsDataSourceConfig.password = password;
    }

    @Value("${spring.datasource.driver-class-name}")
    public void setDriverClassName(String driverClassName) {
        NewWindowsDataSourceConfig.driverClassName = driverClassName;
    }

    @Value(value = "${spring.datasource.initialSize}")
    public void setInitialSize(int initialSize) {
        NewWindowsDataSourceConfig.initialSize = initialSize;
    }

    @Value(value = "${spring.datasource.minIdle}")
    public void setMinIdle(int minIdle) {
        NewWindowsDataSourceConfig.minIdle = minIdle;
    }

    @Value(value = "${spring.datasource.maxActive}")
    public void setMaxActive(int maxActive) {
        NewWindowsDataSourceConfig.maxActive = maxActive;
    }

    @Value(value = "${nw.datasource.maxWait}")
    public void setMaxWait(int maxWait) {
        NewWindowsDataSourceConfig.maxWait = maxWait;
    }
}

 注意@MapperScan的basePackages配置包路径不能有重叠,必须要区分开,否则会有其中一个datasource对应的Mybatis配置加载不到Mapper接口。

 DruidServlet配置一个就行了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值