springbootJava后台SpringBoot

5、SpringBoot整合数据源druid及多数据源使用

2018-10-21  本文已影响167人  小manong

一、阿里巴巴druid数据源简介

1.优势

2.番外篇

二、springboot整合druid使用并完成sql监控

1.maven依赖

<dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid</artifactId>
       <version>1.1.10</version>
  </dependency>

2.数据源相关配置

  server.port=8080
# 数据库访问配置
# 主数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
######################### Druid连接池的配置信息  #################
spring.druid.initialSize=5                                 #初始化连接大小
spring.druid.minIdle=5                                     #最小连接池数量
spring.druid.maxActive=20                                  #最大连接池数量
spring.druid.maxWait=60000                                 #获取连接时最大等待时间,单位毫秒
spring.druid.timeBetweenEvictionRunsMillis=60000           #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.druid.minEvictableIdleTimeMillis=300000             #配置一个连接在池中最小生存的时间,单位是毫秒
spring.druid.validationQuery=SELECT 1 FROM DUAL            #测试连接
spring.druid.testWhileIdle=true                            #申请连接的时候检测,建议配置为true,不影响性能,并且保证安全性
spring.druid.testOnBorrow=false                            #获取连接时执行检测,建议关闭,影响性能
spring.druid.testOnReturn=false                            #归还连接时执行检测,建议关闭,影响性能
spring.druid.poolPreparedStatements=false                  #是否开启PSCache,PSCache对支持游标的数据库性能提升巨大,oracle建议开启,mysql下建议关闭
spring.druid.maxPoolPreparedStatementPerConnectionSize=20  #开启poolPreparedStatements后生效
spring.druid.filters=stat,wall,log4j                       #配置扩展插件,常用的插件有=>stat:监控统计  log4j:日志  wall:防御sql注入
spring.druid.connectionProperties='druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000'  #通过connectProperties属性来打开mergeSql功能;慢SQL记录

注意:可以直接使用上面在配置文件中的配置,然后借助springboot自动装配机制完成配置加载。但是直接默认使用springboot自动加载的话,有时候容易出现bug,最好自己封装下,还可以灵活配置调用。

@Configuration
public class DruidConfiguration {
    
@Configuration
public class DruidConfiguration {
    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${spring.datasource.filters}")
    private String filters;

    @Value("{spring.datasource.connectionProperties}")
    private String connectionProperties;

    @Bean
    @Primary
    public DataSource dataSource() {
        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(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {

        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }

...
}

3.配置druid相关的sql监控

(1)StatViewServlet是一个标准的javax.servlet.http.HttpServlet,使用时候需要注入

 @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        servletRegistrationBean.addInitParameter("allow","127.0.0.1");  //设置ip白名单
        servletRegistrationBean.addInitParameter("deny","192.168.0.19");//设置ip黑名单,优先级高于白名单
        //设置控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername","root");
        servletRegistrationBean.addInitParameter("loginPassword","root");
        //是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean statFilter(){
        //创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

4.测试

二、springboot多数据源使用

1.数据准备阶段

2.application.properties中配置

//主数据源
spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1
spring.datasource.primary.username=root
spring.datasource.primary.password=123456
spring.datasource.primary.driverClassName=com.mysql.jdbc.Driver

spring.datasource.second.url=jdbc:mysql://localhost:3306/test2
spring.datasource.second.username=root
spring.datasource.second.password=123456
spring.datasource.second.driverClassName=com.mysql.jdbc.Driver

3.java配置文件中配置

@Configuration
public class DruidConfiguration {

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${spring.datasource.filters}")
    private String filters;

    @Value("{spring.datasource.connectionProperties}")
    private String connectionProperties;


    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();

        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(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {

        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }

    //根据不同数据库来配置
    //=========================配置primary数据源================
    @Bean(name = "primaryDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary
    public DataSource primaryDatasource() {
        return dataSource();
    }

    @Bean(name = "primaryTransactionManager")
    @Primary
    public DataSourceTransactionManager primaryTransactionManager() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(primaryDatasource());
        return transactionManager;
    }

    @Bean(name = "primaryJdbcTemplate")
    @Primary
    public JdbcTemplate primaryJdbcTemplate(
    ) {
        DataSource dataSource = primaryDatasource();
        return new JdbcTemplate(dataSource);
    }

    //=========================配置second数据源================
    @Bean(name = "secondDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondDatasource() {
        return dataSource();
    }

    @Bean(name = "secondTransactionManager")
    public DataSourceTransactionManager secondTransactionManager() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(secondDatasource());
        return transactionManager;
    }

    @Bean(name = "secondJdbcTemplate")
    public JdbcTemplate secondJdbcTemplate(
    ) {
        DataSource dataSource = secondDatasource();
        return new JdbcTemplate(dataSource);
    }
...}

4.测试controller

@RestController
public class MultiDataSourceController {
    @Qualifier("primaryJdbcTemplate")
    @Autowired
    private JdbcTemplate primaryJdbcTemplate;

    @Qualifier("secondJdbcTemplate")
    @Autowired
    private JdbcTemplate secondJdbcTemplate;
//测试primary
    @RequestMapping("/primary")
    public String primaryDatasourceTest(){
        String sql="select * from user";
        List<User> primaryUserList = primaryJdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        return JSON.toJSONString(primaryUserList);
    }
//测试second
    @RequestMapping("/second")
    public String secondDatasourceTest(){
        String sql="select * from user";
        List<User> secondUserList = secondJdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        return JSON.toJSONString(secondUserList);
    }
}

5.测试

上一篇下一篇

猜你喜欢

热点阅读