SpringBoot集成Druid连接池

  sre

pom.xml

<!-- 数据库依赖 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.21</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.13</version>
</dependency>
<!-- JDBC 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

application.yml

server:
  port: 8888

spring:
  application:
    name: druid
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/dbtest?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
      username: root
      password: 123456
      initial-size: 10
      max-active: 100
      min-idle: 10
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      max-evictable-idle-time-millis: 60000
      validation-query: SELECT 1 FROM DUAL
      # validation-query-timeout: 5000
      test-on-borrow: false
      test-on-return: false
      test-while-idle: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      filters: stat,wall
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*

DruidConfig.java Druid数据库连接池配置文件

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class DruidConfig {
    private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);

    @Value("{spring.datasource.druid.url}")
    private String dbUrl;

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

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

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

    @Value("{spring.datasource.druid.initial-size}")
    private int initialSize;

    @Value("{spring.datasource.druid.max-active}")
    private int maxActive;

    @Value("{spring.datasource.druid.min-idle}")
    private int minIdle;

    @Value("{spring.datasource.druid.max-wait}")
    private int maxWait;

    @Value("{spring.datasource.druid.pool-prepared-statements}")
    private boolean poolPreparedStatements;

    @Value("{spring.datasource.druid.max-pool-prepared-statement-per-connection-size}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("{spring.datasource.druid.time-between-eviction-runs-millis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("{spring.datasource.druid.min-evictable-idle-time-millis}")
    private int minEvictableIdleTimeMillis;

    @Value("{spring.datasource.druid.max-evictable-idle-time-millis}")
    private int maxEvictableIdleTimeMillis;

    @Value("{spring.datasource.druid.validation-query}")
    private String validationQuery;

    @Value("{spring.datasource.druid.test-while-idle}")
    private boolean testWhileIdle;

    @Value("{spring.datasource.druid.test-on-borrow}")
    private boolean testOnBorrow;

    @Value("{spring.datasource.druid.test-on-return}")
    private boolean testOnReturn;

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

    @Value("{spring.datasource.druid.connection-properties}")
    private String connectionProperties;

    /**
     * Druid 连接池配置
     */
    @Bean     //声明其为Bean实例
    public DruidDataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (Exception e) {
            logger.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties(connectionProperties);
        return datasource;
    }
    /**
     * JDBC操作配置
     */
    @Bean(name = "dataOneTemplate")
    public JdbcTemplate jdbcTemplate (@Autowired DruidDataSource dataSource){
        return new JdbcTemplate(dataSource) ;
    }

    /**
     * 配置 Druid 监控界面
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean srb =
                new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        //设置控制台管理用户
        srb.addInitParameter("loginUsername","root");
        srb.addInitParameter("loginPassword","root");
        //是否可以重置数据
        srb.addInitParameter("resetEnable","false");
        return srb;
    }
    @Bean
    public FilterRegistrationBean statFilter(){
        //创建过滤器
        FilterRegistrationBean frb =
                new FilterRegistrationBean(new WebStatFilter());
        //设置过滤器过滤路径
        frb.addUrlPatterns("/*");
        //忽略过滤的形式
        frb.addInitParameter("exclusions",
                "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return frb;
    }
}

DruidController.java 测试sql

@RestController
public class DruidController {
    private static final Logger LOG = LoggerFactory.getLogger(DruidController.class);

    @Resource
    private JdbcTemplate jdbcTemplate ;

    @RequestMapping("/druidData")
    public String druidData (){
        String sql = "SELECT COUNT(1) FROM wp_posts" ;
        Integer countOne = jdbcTemplate.queryForObject(sql,Integer.class) ;
        // countOne==2
        LOG.info("countOne=="+countOne);
        return "success" ;
    }
}

访问http://127.0.0.1:8888/druidDate可以看到结果

2020-12-23 17:26:14.898  INFO 17572 --- [nio-8888-exec-3] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2020-12-23 17:26:15.046  INFO 17572 --- [nio-8888-exec-3] c.boot.druid.controller.DruidController  : countOne==2899
2020-12-23 17:26:41.805  INFO 17572 --- [nio-8888-exec-7] c.boot.druid.controller.DruidController  : countOne==2899
2020-12-23 17:26:44.322  INFO 17572 --- [nio-8888-exec-9] c.boot.druid.controller.DruidController  : countOne==2899
2020-12-23 17:26:44.489  INFO 17572 --- [io-8888-exec-10] c.boot.druid.controller.DruidController  : countOne==2899
2020-12-23 17:26:45.288  INFO 17572 --- [nio-8888-exec-2] c.boot.druid.controller.DruidController  : countOne==2899

访问http://127.0.0.1:8888/druid/index.html

用户名root密码root

LEAVE A COMMENT

Captcha Code