springboot 使用Druid数据库连接池

一、Druid是什么?

Druid是阿里巴巴发的号称为监控而生的数据库连接池。

Druid是一个数据库连接池。在功能、性能、扩展性上都超过了其他数据库连接池,包括DBCP等。

同时,Druid是一个jdbc组件,包括三部分:

    基于Filter-Chain模式的插件体系。

    DruidDataSource 高效可管理的数据库连接池。

    SQLParser

二、Druid的功能

1、充当数据库连接池。
2、可以监控数据库访问性能,可以精确到访问多长时间。
3、获得SQL执行日志。

三、配置

创建好项目后导入相关依赖

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

配置application.yml

spring:
  datasource:
    #1.JDBC
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
    druid:
      #2.连接池配置
      #初始化连接池的连接数量 大小,最小,最大
      initial-size: 5
      min-idle: 5
      max-active: 20
      #配置获取连接等待超时的时间
      max-wait: 60000
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 30000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: true
      test-on-return: false
      # 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filter:
        stat:
          merge-sql: true
          slow-sql-millis: 5000
      #3.基础监控配置
      web-stat-filter:
        enabled: true
        url-pattern: /*
        #设置不统计哪些URL
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true
        session-stat-max-count: 100
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: true
        #设置监控页面的登录名和密码
        login-username: admin
        login-password: admin
        allow: 127.0.0.1
        #deny: 192.168.1.100

 这里会有坑

配置好后运行http://localhost:8081/springboot/druid/login.html

会报错

Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: 
        The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. 
        You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

这是因为版本不和,将mysql的版本改为5.1.44就OK了。

运行如下

猜你喜欢

转载自blog.csdn.net/oydl_1234/article/details/87637907