论坛首页 Java企业应用论坛

Spring boot配置多数据源

浏览 3183 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2017-06-26  

配置第一个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.movit.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;

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

    /**
     * 注册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.movit.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接口。

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics