Spring Boot之默认连接池配置策略

注意:如果我们使用spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa “starters”坐标,Spring Boot将自动配置HikariCP连接池,

   因为HikariCP在性能和并发性相比其他连接池都要好。

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

一、默认连接池策略

1.如果可以得到HikariCP连接池类,就优先配置HikariCP

2.否则,如果Tomcat pooling类可以得到,则使用它

3.如果上面两个都拿不到,则配置其他连接池,比如Commons DBCP2 

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

yml文件:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/heimdallr?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
    username: root
    password: 123
    driver-class-name: com.mysql.jdbc.Driver
#   Spring Boot官方推荐的数据库连接池是Hikari,从一些第三方的评测结果看,Hikari的性能比Druid要好,但是Druid自带各种监控工具,背后又有阿里一直在为它背书
#   hikari数据源配置,
    hikari:
      connection-test-query: SELECT 1 FROM DUAL
      connection-timeout: 30000
      maximum-pool-size: 20
      max-lifetime: 1800000
      minimum-idle: 5

二、自己指定连接池

通过设置spring.datasource.type属性,可以跳过默认连接池选择策略,比如卑职druid连接池

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/heimdallr?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
    username: root
    password: 123
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
    max-idle: 10
    max-wait: 1000
    min-idle: 5
    initial-size: 5
    output.ansi.enabled: always
# 配置druid
    druid:
# 配置获取连接等待超时的时间
      maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM t_user
      testWhileIdle: true
      testOnBorrow: true
      testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,log4j
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#     useGlobalDataSourceStat: true

猜你喜欢

转载自www.cnblogs.com/756623607-zhang/p/9453394.html