继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Spring Boot使用Druid连接池

艾贺521
关注TA
已关注
手记 292
粉丝 1.1万
获赞 1544

Druid是Java语言中最好的数据库连接池。Druid相比于其他的数据库连接池,有两大特性:

  • 监控数据库,有利于分析线上数据库问题
  • 更容易扩展,同时也很高效。

今天演示一下Spring Boot集成Druid。

实战

  1. 添加Maven依赖。
    Spring Boot版本使用的是1.x的,2.x的版本druid starter还不支持。不过自定义也是没问题的。

        <!--starter-web 方便我们查看效果-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--使用Mybatis也可以,druid提供的只是连接池-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.6</version>
        </dependency>

[图片上传失败...(image-19131f-1528898404637)]

  1. 配置Druid

Druid应用的配置。

server:
  port: 9011

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    druid:
      initial-size: 5
      max-active: 10
      min-idle: 5
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      validation-query: select 1
      validation-query-timeout: 60000
      test-on-borrow: false
      test-on-return: false
      test-while-idle: true
      time-between-eviction-runs-millis: 60000
      filter:
        stat:
          log-slow-sql: true
          db-type: mysql
          slow-sql-millis: 2000
      stat-view-servlet:
        login-username: druid
        login-password: druid
        allow: 127.0.0.1
        url-pattern: /druid/*
      username: root
      password: 123456
      url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8

通过JavaBean的配置更灵活一些,我们通过JavaBean来配置。

@Configuration
public class DruidConfig {

    @Bean
    public JdbcTemplate jdbcTemplate(){
        return new JdbcTemplate(druidDataSource());
    }

    // ConfigurationProperties可以直接把应用配置的spring.datasource.druid属性开头的值注入到DruidDataSource中
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    @Bean(initMethod = "init",destroyMethod = "close")
    public DruidDataSource druidDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();

        // 添加druid的监控过滤器,当前只演示监控的功能,因此只有一个过滤器,可以实现多个过滤器
        LinkedList<Filter> filtersList = new LinkedList();
        filtersList.add(filter());
        druidDataSource.setProxyFilters(filtersList);

        return druidDataSource;
    }

    @Bean
    public Filter filter(){
        StatFilter statFilter = new StatFilter();
        // SQL执行时间超过2s种的被判定为慢日志
        statFilter.setSlowSqlMillis(2000);
        //显示慢日志
        statFilter.setLogSlowSql(true);
        //合并SQL,有时,一些相同的慢日志过多影响阅读,开启合并功能
        statFilter.setMergeSql(true);
        return statFilter;
    }

    // 监控的面板
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
       // 注册自己的Sevlet
        return new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
    }

}
  1. 新建SQL执行测试
    使用JDBCTeplate选取数据库中的数据,我们只是演示Druid的监控效果。

    
    @RestController
    @SpringBootApplication
    public class DaoApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(DaoApplication.class,args);
    }
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @RequestMapping("/test")
    public List test(){
        final List<Integer> idList = new LinkedList<Integer>();
        jdbcTemplate.query("select * from sh_test1", new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                  idList.add(rs.getInt(1));
            }
        });
    
        return idList;
    }

}



4. 运行查看效果
![image.png](https://upload-images.jianshu.io/upload_images/426671-cc585c7173da50b7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![image.png](https://upload-images.jianshu.io/upload_images/426671-b40fecba4cd5e126.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![image.png](https://upload-images.jianshu.io/upload_images/426671-17ed12e185a4f7b5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

5. 演示完毕
到这一步,Druid已经可以在Spring Boot中使用了,Druid提供了很多监控的选项,文章篇幅有限, 只介绍一下Druid集成Spring Boot的用法。

### 最后
这篇文章演示了一下Druid在SpringBoot中的使用。有关Druid的使用请看下面的参考。

### 参考
- [Druid常见用法] (https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)
打开App,阅读手记
4人推荐
发表评论
随时随地看视频慕课网APP