欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring boot 集成 Druid 数据源过程详解

程序员文章站 2023-11-21 17:52:58
druid是阿里开源的一个jdbc应用组件,其中包括三部分: druiddriver:代理driver,能够提供基于filter-chain模式的插件体系。...

druid是阿里开源的一个jdbc应用组件,其中包括三部分:

  • druiddriver:代理driver,能够提供基于filter-chain模式的插件体系。
  • druiddatasource:高效可管理的数据库连接池。
  • sqlparser:实用sql语法分析

官方文档:

依赖

pom.xml

druid spring boot starter是阿里官方提供的spring boot插件,用于在spring boot项目中集成druid数据库连接池和监控

<!-- druid -->
<dependency>
  <groupid>com.alibaba</groupid>
  <artifactid>druid-spring-boot-starter</artifactid>
  <version>1.1.9</version>
</dependency>
<!-- log4j -->
<dependency>
  <groupid>log4j</groupid>
  <artifactid>log4j</artifactid>
  <version>1.2.17</version>
</dependency>

配置

application.yml

server:
 port: 8001

spring:
 datasource:
  name: druiddatasource
  type: com.alibaba.druid.pool.druiddatasource
  druid:
   driver-class-name: com.mysql.cj.jdbc.driver
   url: jdbc:mysql://localhost:3306/coisini?useunicode=true&zerodatetimebehavior=converttonull&autoreconnect=true&characterencoding=utf-8&servertimezone=gmt%2b8
   username: root
   password: sunday
   filters: stat,wall,log4j,config
   max-active: 100
   initial-size: 1
   max-wait: 60000
   min-idle: 1
   time-between-eviction-runs-millis: 60000
   min-evictable-idle-time-millis: 300000
   validation-query: select 'x'
   test-while-idle: true
   test-on-borrow: false
   test-on-return: false
   pool-prepared-statements: true
   max-open-prepared-statements: 50
   max-pool-prepared-statement-per-connection-size: 20

druiddatasourceproperties.class

配置类对druid进行自定义属性配置

@configurationproperties(prefix = "spring.datasource.druid")
public class druiddatasourceproperties {

  // jdbc
  private string driverclassname;
  private string url;
  private string username;
  private string password;
  // jdbc connection pool
  private int initialsize;
  private int minidle;
  private int maxactive = 100;
  private long maxwait;
  private long timebetweenevictionrunsmillis;
  private long minevictableidletimemillis;
  private string validationquery;
  private boolean testwhileidle;
  private boolean testonborrow;
  private boolean testonreturn;
  private boolean poolpreparedstatements;
  private int maxpoolpreparedstatementperconnectionsize;
  // filter
  private string filters;

  public int getinitialsize() {
    return initialsize;
  }
  public void setinitialsize(int initialsize) {
    this.initialsize = initialsize;
  }
  public int getminidle() {
    return minidle;
  }
  public void setminidle(int minidle) {
    this.minidle = minidle;
  }
  public int getmaxactive() {
    return maxactive;
  }
  public void setmaxactive(int maxactive) {
    this.maxactive = maxactive;
  }
  public long getmaxwait() {
    return maxwait;
  }
  public void setmaxwait(long maxwait) {
    this.maxwait = maxwait;
  }
  public long gettimebetweenevictionrunsmillis() {
    return timebetweenevictionrunsmillis;
  }
  public void settimebetweenevictionrunsmillis(long timebetweenevictionrunsmillis) {
    this.timebetweenevictionrunsmillis = timebetweenevictionrunsmillis;
  }
  public long getminevictableidletimemillis() {
    return minevictableidletimemillis;
  }
  public void setminevictableidletimemillis(long minevictableidletimemillis) {
    this.minevictableidletimemillis = minevictableidletimemillis;
  }
  public string getvalidationquery() {
    return validationquery;
  }
  public void setvalidationquery(string validationquery) {
    this.validationquery = validationquery;
  }
  public boolean istestwhileidle() {
    return testwhileidle;
  }
  public void settestwhileidle(boolean testwhileidle) {
    this.testwhileidle = testwhileidle;
  }
  public boolean istestonborrow() {
    return testonborrow;
  }
  public void settestonborrow(boolean testonborrow) {
    this.testonborrow = testonborrow;
  }
  public boolean istestonreturn() {
    return testonreturn;
  }
  public void settestonreturn(boolean testonreturn) {
    this.testonreturn = testonreturn;
  }
  public boolean ispoolpreparedstatements() {
    return poolpreparedstatements;
  }
  public void setpoolpreparedstatements(boolean poolpreparedstatements) {
    this.poolpreparedstatements = poolpreparedstatements;
  }
  public int getmaxpoolpreparedstatementperconnectionsize() {
    return maxpoolpreparedstatementperconnectionsize;
  }
  public void setmaxpoolpreparedstatementperconnectionsize(int maxpoolpreparedstatementperconnectionsize) {
    this.maxpoolpreparedstatementperconnectionsize = maxpoolpreparedstatementperconnectionsize;
  }
  public string getfilters() {
    return filters;
  }
  public void setfilters(string filters) {
    this.filters = filters;
  }
  public string getdriverclassname() {
    return driverclassname;
  }
  public void setdriverclassname(string driverclassname) {
    this.driverclassname = driverclassname;
  }
  public string geturl() {
    return url;
  }
  public void seturl(string url) {
    this.url = url;
  }
  public string getusername() {
    return username;
  }
  public void setusername(string username) {
    this.username = username;
  }
  public string getpassword() {
    return password;
  }
  public void setpassword(string password) {
    this.password = password;
  }
}

druid spring starter简化了很多配置,如果默认配置不满足你的需求,可以自定义配置,参考文档:

配置servlet和filter

druidconfig.class

@enableconfigurationproperties:用于导入druid的配置信息

@configuration
@enableconfigurationproperties({druiddatasourceproperties.class})
public class druidconfig {
  @autowired
  private druiddatasourceproperties properties;
  @bean
  @conditionalonmissingbean
  public datasource druiddatasource() {
    druiddatasource druiddatasource = new druiddatasource();
    druiddatasource.setdriverclassname(properties.getdriverclassname());
    druiddatasource.seturl(properties.geturl());
    druiddatasource.setusername(properties.getusername());
    druiddatasource.setpassword(properties.getpassword());
    druiddatasource.setinitialsize(properties.getinitialsize());
    druiddatasource.setminidle(properties.getminidle());
    druiddatasource.setmaxactive(properties.getmaxactive());
    druiddatasource.setmaxwait(properties.getmaxwait());
    druiddatasource.settimebetweenevictionrunsmillis(properties.gettimebetweenevictionrunsmillis());
    druiddatasource.setminevictableidletimemillis(properties.getminevictableidletimemillis());
    druiddatasource.setvalidationquery(properties.getvalidationquery());
    druiddatasource.settestwhileidle(properties.istestwhileidle());
    druiddatasource.settestonborrow(properties.istestonborrow());
    druiddatasource.settestonreturn(properties.istestonreturn());
    druiddatasource.setpoolpreparedstatements(properties.ispoolpreparedstatements());
    druiddatasource.setmaxpoolpreparedstatementperconnectionsize(properties.getmaxpoolpreparedstatementperconnectionsize());
    try {
      druiddatasource.setfilters(properties.getfilters());
      druiddatasource.init();
    } catch (sqlexception e) {
      e.printstacktrace();
    }
    return druiddatasource;
  }

  /**
   * 注册servlet信息, 配置监控视图
   * @return
   */
  @bean
  @conditionalonmissingbean
  public servletregistrationbean<servlet> druidservlet() {
    servletregistrationbean<servlet> servletregistrationbean = new servletregistrationbean<servlet>(new statviewservlet(), "/druid/*");

    //白名单:
//    servletregistrationbean.addinitparameter("allow","127.0.0.1,139.196.87.48");
    //ip黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:sorry, you are not permitted to view this page.
    servletregistrationbean.addinitparameter("deny","192.168.1.119");
    //登录查看信息的账号密码, 用于登录druid监控后台
    servletregistrationbean.addinitparameter("loginusername", "admin");
    servletregistrationbean.addinitparameter("loginpassword", "admin");
    //是否能够重置数据.
    servletregistrationbean.addinitparameter("resetenable", "true");
    return servletregistrationbean;
  }

  /**
   * 注册filter信息, 监控拦截器
   * @return
   */
  @bean
  @conditionalonmissingbean
  public filterregistrationbean<filter> filterregistrationbean() {
    filterregistrationbean<filter> filterregistrationbean = new filterregistrationbean<filter>();
    filterregistrationbean.setfilter(new webstatfilter());
    filterregistrationbean.addurlpatterns("/*");
    filterregistrationbean.addinitparameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return filterregistrationbean;
  }
}

resources目录下添加log4j参数配置文件

### set log levels ###  
log4j.rootlogger = info,debug, console, infofile, errorfile ,debugfile,mail 
locationinfo=true  
log4j.appender.console = org.apache.log4j.consoleappender 
log4j.appender.console.target = system.out 
log4j.appender.console.layout = org.apache.log4j.patternlayout 
log4j.appender.console.layout.conversionpattern =[%d{yyyy-mm-dd hh:mm:ss,sss}]-[%p]:%m  %x %n 
log4j.appender.infofile = org.apache.log4j.dailyrollingfileappender 
log4j.appender.infofile.threshold = info 
log4j.appender.infofile.file = c:/logs/log
log4j.appender.infofile.datepattern = '.'yyyy-mm-dd'.log' 
log4j.appender.infofile.append=true
log4j.appender.infofile.layout = org.apache.log4j.patternlayout 
log4j.appender.infofile.layout.conversionpattern =[%d{yyyy-mm-dd hh:mm:ss,sss}]-[%p]:%m %x %n 
log4j.appender.errorfile = org.apache.log4j.dailyrollingfileappender 
log4j.appender.errorfile.threshold = error 
log4j.appender.errorfile.file = c:/logs/error 
log4j.appender.errorfile.datepattern = '.'yyyy-mm-dd'.log' 
log4j.appender.errorfile.append=true 
log4j.appender.errorfile.layout = org.apache.log4j.patternlayout 
log4j.appender.errorfile.layout.conversionpattern =[%d{yyyy-mm-dd hh:mm:ss,sss}]-[%p]:%m %x %n
log4j.appender.debugfile = org.apache.log4j.dailyrollingfileappender 
log4j.appender.debugfile.threshold = debug 
log4j.appender.debugfile.file = c:/logs/debug 
log4j.appender.debugfile.datepattern = '.'yyyy-mm-dd'.log' 
log4j.appender.debugfile.append=true 
log4j.appender.debugfile.layout = org.apache.log4j.patternlayout 
log4j.appender.debugfile.layout.conversionpattern =[%d{yyyy-mm-dd hh:mm:ss,sss}]-[%p]:%m %x %n

编译运行

启动应用,访问http://localhost:8001/druid/login.html,如下:

Spring boot 集成 Druid 数据源过程详解

用户名与密码为driudconfig中配置的登录账号和密码:admin/admin

Spring boot 集成 Druid 数据源过程详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。