【SpringBoot 2.x】 开发实战day10,整合springboot 与 Druid连接池(一),单数据源

一、关于druid(德鲁伊)

作为开发人员,对Druid应该都不陌生,druid自称是Java语言中最好的数据库连接池,其本身作为阿里团队的御用连接池,也证明了其性能上的实力。配置方面,从spingBoot 2.0开始,可以使用一个配置文件直接搞定,不用再定义Config类(多数据源依旧需要配置Config注册,会再写篇博客记录配置过程),使代码更加简洁,监控方面,druid自带UI监控页面,可以使用自定义访问地址和账号密码,使SQL监控更加容易。对比其他连接池(C3P0、DBCP等等,其优势就在性能和监控上)
二、如何配置Druid

        添加maven依赖
        添加application.yml配置
        简单测试查看Druid监控情况

本次整合环境: JDK 8 、springBoot 2.1.8、Mybatis 2.1.0、Mysql、Druid
1、添加Maven依赖

<!-- Druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<!-- mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>

这里强调一点是:我们选择了官方提供的 druid-spring-boot-starter 插件,相比原版本的引用druid依赖,依赖配置文件不再需要定义Config类,监控和过滤器也通过配置来实现,同时,在使用IDEA编辑application.yml(或者application.properties)文件也提供了相关代码提示。
2、添加application.yml配置(针对单数据源)

这里列举出很多配置,都有注释,方便查看合理配置,文章最后给出官方配置文档

server:
  port: 8888
debug: false

spring:

  # json 输出格式化与时间格式化
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss SSS
    time-zone: GMT+8
    serialization:
      indent-output: true
  mvc:
    date-format: yyyy-MM-dd

  # datasource
  datasource:
      druid:
        url: jdbc:mysql://localhost:3306/scott?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.Driver

        # Druid连接池配置
        # 数据库类型为mysql
        db-type: mysql
        # 启动时初始化5个连接
        initialSize: 5
        # 最小空闲连接5个
        min-idle: 5
        # 最大连接数量20
        max-active: 20
        # 获取连接等待时间60秒,超出报错
        max-wait: 60000
        # 每60秒执行一次连接回收器
        time-between-eviction-runs-millis: 60000
        # 5分钟内没有任何操作的空闲连接会被回收
        min-evictable-idle-time-millis: 300000
        # 验证连接有效性的SQL
        validation-query: select 'x'
        # 空闲时校验,建议开启
        test-while-idle: true
        # 使用中是否校验有效性,推荐关闭
        test-on-borrow: false
        # 归还连接时校验有效性,推荐关闭
        test-on-return: false
        # oracle 推荐使用
        pool-prepared-statements: false
        # 设置过滤器,stat用于接收状态,wall用于防止SQL注入
        filters: stat,wall

        # Druid监控配置
        # WebStatFilter配置
        web-stat-filter:
          # 是否启用StatFilter, 默认值true
          enabled: true
          # URL白名单
          url-pattern: /*
          # 过滤器排除掉的静态资源,yml配置需要用引号""
          exclusions:  "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
          # session 统计功能
          session-stat-enable: false
          # 最大session数
          session-stat-max-count: 1000
          # 你可以配置principalSessionName, 使得druid能够知道当前的session的用户是谁
          principal-session-name: admin
          # druid能够知道当前的cookie的用户是谁
          principal-cookie-name: admin
          # 配置profileEnable能够监控单个url调用的sql列表
          profile-enable: true
        # StatViewServlet配置 :展示Druid的统计信息, StatViewServlet的用途包括: 1.提供监控信息展示的html页面; 2.提供监控信息的JSON API
        stat-view-servlet:
          # 是否启用StatViewServlet, 默认值true
          enabled: true
          # 根据配置中的url-pattern来访问内置监控页面,内置监控页面的地址是{上下文}/druid
          url-pattern: /druid/*
          # 允许清空统计数据
          reset-enable: false
          # 配置登录用户名
          login-username: administrator
          # 配置登录密码
          login-password: 123456
          # 如果你需要做访问控制, 可以配置allow和deny这两个参数
          # deny优先于allow, 如果在deny列表中, 就算在allow列表中, 也会被拒绝. 如果allow没有配置或者为空, 则允许所有访问.
          allow: 127.0.0.1
          deny: 10.1.1.110

        filter:
          stat:
            # 是否启用statFilter
            enabled: true
            # 数据库类型
            db-type: mysql
            # 是否开启慢sql日志,针对执行效率低的SQL记录日志
            log-slow-sql: true
            # 设置超过指定时间为慢SQL
            slow-sql-millis: 2000

          # WallFilter配置
          wall:
            # 是否启用WallFilter, 默认值true
            enabled: true
            # 数据库类型
            db-type: mysql
            config:
              delete-allow: false
              drop-table-allow: false
              alter-table-allow: false
              truncate-allow: false
              # 是否允许非以上基本语句的其他语句, 缺省关闭, 通过这个选项就能够屏蔽DDL
              none-base-statement-allow: false
              # 检查UPDATE语句是否无where条件, 这是有风险的, 但不是SQL注入类型的风险
              update-where-none-check: true
              # SELECT ... INTO OUTFILE 是否允许, 缺省是禁止的
              select-into-outfile-allow: false
              # 是否允许调用Connection.getMetadata方法, 这个方法调用会暴露数据库的表信息
              metadata-allow: true
            # 对被认为是攻击的SQL进行LOG.error输出
            log-violation: true
            # 对被认为是攻击的SQL抛出SQLExcepton
            throw-exception: true

# mybatis
mybatis:
  # 核心配置文件,指定的是mybatis-config.xml
  config-location: classpath:/mybatis/mybatis-config.xml
  # 指定mapper映射文件,全注解方式不需要
  mapper-locations: classpath:/mybatis/mapper/*Mapper.xml

# 打印sql
logging:
  level:
     cn.gcheng.springboot.mapper : debug

3、简单测试查看Druid监控情况

启动项目成功,没有问题。

2019-10-10 17:03:49 INFO  [main]  c.g.s.SpringbootApplication - Starting SpringbootApplication on T7TYF9ZQGHYS78N with PID 7712 (E:\workspace\SpringBoot-Modules-Study\springboot-Day10\target\classes started by Administrator in E:\workspace\SpringBoot-Modules-Study)
2019-10-10 17:03:49 INFO  [main]  c.g.s.SpringbootApplication - No active profile set, falling back to default profiles: default
2019-10-10 17:03:51 INFO  [main]  o.s.b.w.e.t.TomcatWebServer - Tomcat initialized with port(s): 8888 (http)
2019-10-10 17:03:51 INFO  [main]  o.a.c.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8888"]
2019-10-10 17:03:51 INFO  [main]  o.a.c.core.StandardService - Starting service [Tomcat]
2019-10-10 17:03:51 INFO  [main]  o.a.c.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.24]
2019-10-10 17:03:51 INFO  [main]  o.a.c.c.C.[.[localhost].[/] - Initializing Spring embedded WebApplicationContext
2019-10-10 17:03:51 INFO  [main]  o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1878 ms
2019-10-10 17:03:51 INFO  [main]  c.a.d.s.b.a.DruidDataSourceAutoConfigure - Init DruidDataSource
2019-10-10 17:03:52 INFO  [main]  c.a.druid.pool.DruidDataSource - {dataSource-1} inited
2019-10-10 17:03:52 INFO  [main]  o.s.s.c.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
2019-10-10 17:03:52 INFO  [main]  o.a.c.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8888"]
2019-10-10 17:03:52 INFO  [main]  o.s.b.w.e.t.TomcatWebServer - Tomcat started on port(s): 8888 (http) with context path ''
2019-10-10 17:03:52 INFO  [main]  c.g.s.SpringbootApplication - Started SpringbootApplication in 4.154 seconds (JVM running for 4.791)

    根据 spring.datasource.druid.stat-view-servlet.url-pattern=/druid/* 配置,
    查看 Druid 监控的地址是 {上下文}/druid
    登录的用户名和密码分别由 spring.datasource.druid.stat-view-servlet.login-username 和 spring.datasource.druid.stat-view-servlet.login-password 设定。

例如自己的配置:输入http://localhost:8888/druid,登陆,查看监控数据即可。
————————————————
原文链接:https://blog.csdn.net/lgc592519828/article/details/103599506

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值