亲宝软件园·资讯

展开

springboot集成druid连接池配置的方法

我吃包菜 人气:2
这篇文章主要介绍了springboot集成druid连接池配置的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

在开发项目中如果数据库选型为mysql,很大概率下连接池会使用druid
这里介绍springboot集成durid

springboot : 2.1.9
druid : 1.1.10

案例地址

github地址

springboot集成druid配置

需要引入的pom

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

需要在application.yaml中添加一些配置

spring:
 datasource:
  type: com.alibaba.druid.pool.DruidDataSource
  driver-class-name: com.mysql.cj.jdbc.Driver
  platform: mysql
  url: jdbc:mysql://127.0.0.1:3306/xxx?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
  username: root
  password: 123456
  initialSize: 5
  minIdle: 5
  maxActive: 20
  maxWait: 60000
  timeBetweenEvictionRunsMillis: 60000
  minEvictableIdleTimeMillis: 300000
  validationQuery: SELECT1FROMDUAL
  testWhileIdle: true
  testOnBorrow: false
  testOnReturn: false
  filters: stat,wall,log4j
  logSlowSql: true 

到此springboot就集成的druid的配置 可以直接使用

springboot添加druid监控平台配置类

DruidConfiguration

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.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 数据库链接池druid监控平台的配置
 * 访问路径 http://localhost:8080/druid/index.html
 *
 */
@Configuration
public class DruidConfiguration {

  private static final Logger logger = LoggerFactory.getLogger(DruidConfiguration.class);

  @Bean
  public ServletRegistrationBean druidServlet() {
    logger.info("init Druid Servlet Configuration ");
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    // IP白名单
//    servletRegistrationBean.addInitParameter("allow", "*");
    // IP黑名单(共同存在时,deny优先于allow)
//    servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
    //控制台管理用户
    servletRegistrationBean.addInitParameter("loginUsername", "admin");
    servletRegistrationBean.addInitParameter("loginPassword", "admin");
    //是否能够重置数据 禁用HTML页面上的“Reset All”功能
    servletRegistrationBean.addInitParameter("resetEnable", "false");
    return servletRegistrationBean;
  }
  @Bean
  public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
    filterRegistrationBean.addUrlPatterns("/*");
    filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return filterRegistrationBean;
  }
}

测试界面

在这里插入图片描述

监控界面的详细使用说明有待大家按需求进行挖掘

加载全部内容

相关教程
猜你喜欢
用户评论