springBoot多数据源 + druid 监控配置

springBoot多数据源 + druid 监控配置

1. pom文件引入依赖

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.23</version>
        </dependency>

2. 配置文件配置数据源信息

#db mysql
spring.datasource.master.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.master.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.master.url=jdbc:mysql://dbIP:3306/dbName?characterEncoding=utf-8&useSSL=true&noAccessToProcedureBodies=true&allowMultiQueries=true
spring.datasource.master.username=****
spring.datasource.master.password=*****
# 数据库连接池配置
spring.datasource.master.initialSize= 5
spring.datasource.master.minIdle= 5
spring.datasource.master.maxActive= 500
spring.datasource.master.maxWait= 60000
spring.datasource.master.timeBetweenEvictionRunsMillis= 60000
spring.datasource.master.minEvictableIdleTimeMillis= 300000
spring.datasource.master.validationQuery= SELECT 1
spring.datasource.master.testWhileIdle= true
spring.datasource.master.testOnBorrow= false
spring.datasource.master.testOnReturn= false
spring.datasource.master.poolPreparedStatements= true
### 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.master.filters= stat,wall,log4j
spring.datasource.master.maxPoolPreparedStatementPerConnectionSize= 20
spring.datasource.master.useGlobalDataSourceStat= true
spring.datasource.master.connectionProperties= druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500


#db sqlsever
spring.datasource.other.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.other.driver-class-name= com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.other.url=jdbc:sqlserver://dbIP:1433;DatabaseName=dbName
spring.datasource.other.username=****
spring.datasource.other.password=*****

3. 配置DataProperties

@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.master")
public class DataProperties {
    String driverClassName;
    String url;
    String username;
    String password;
}

4. 配置DataSourceConfig

@Configuration
@MapperScan(basePackages = "com.xxx.xxx.xxx.xxxmapper",sqlSessionTemplateRef = "sqlSessionTemplate")
public class DataSourceConfig {

    @Autowired
    private DataProperties firstprop;

    //创建数据源
    @Bean(name="dataSource")
    public DataSource getFirstDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(firstprop.url);
        druidDataSource.setDbType("mysql");
        druidDataSource.setDriverClassName(firstprop.driverClassName);
        druidDataSource.setUsername(firstprop.username);
        druidDataSource.setPassword(firstprop.password);
        return druidDataSource;
//        DataSource build = DataSourceBuilder.create()
//                .driverClassName(firstprop.driverClassName)
//                .url(firstprop.url)
//                .username(firstprop.username)
//                .password(firstprop.password).build();
//        return build;
    }

    //创建SqlSessionFactory
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/mysqlmapper/*.xml"));
        return bean.getObject();
    }

    //创建事务管理器
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager firstTransactionManager(@Qualifier("dataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    //创建SqlSessionTemplate
    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws  Exception{
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * 创建一个新的事务管理器
     * @param dataSource
     * @return
     */
    @Bean(name = "nameTransactionTemplate1")
    public NamedParameterJdbcTemplate nameTransactionManager(
            @Qualifier("dataSource") DataSource dataSource) {
        return new NamedParameterJdbcTemplate(dataSource);
    }

    private Class getType(String type){
        try {
            return Class.forName(type);
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        return null;
    }

}

5. 配置DruidConfig

@Configuration
public class DruidConfig {
    @Bean(destroyMethod = "close", initMethod = "init")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 配置监控服务器
     * @return 返回监控注册的servlet对象
     * @return
     */
    @Bean
    public ServletRegistrationBean druidStatViewServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        Map<String, String> initParams = new HashMap<>();
        // 可配的属性都在 StatViewServlet 和其父类下
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "admin");
        servletRegistrationBean.setInitParameters(initParams);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean druidWebStatFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*");
        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        return filterRegistrationBean;
    }


    /**
     * 配置监控服务器
     * @return 返回监控注册的servlet对象
     * @author SimpleWu
//     */
//    @Bean
//    public ServletRegistrationBean statViewServlet() {
//        return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
//    }

//    @Bean
//    public ServletRegistrationBean druidServlet() {
//        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
//        servletRegistrationBean.setServlet(new StatViewServlet());
//        servletRegistrationBean.addUrlMappings("/druid/*");
//        Map<String, String> initParameters = new HashMap<>();
//        initParameters.put("loginUsername", userName);// 用户名
//        initParameters.put("loginPassword", password);// 密码
//        initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
//        servletRegistrationBean.setInitParameters(initParameters);
//        return servletRegistrationBean;
//    }

//    @Bean
//    public FilterRegistrationBean filterRegistrationBean() {
//        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
//        filterRegistrationBean.setFilter(new WebStatFilter());
//        filterRegistrationBean.addUrlPatterns("/*");
//        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
//        return filterRegistrationBean;
//    }
}

第二个数据源就不配了

详情参考:https://segmentfault.com/a/1190000015564484?utm_source=sf-similar-article

posted @ 2021-12-08 16:10  潘小伟  阅读(942)  评论(0编辑  收藏  举报