6

配置 Druid 数据源及密码加密-SpringBoot 2.7 实战基础 - 程序员优雅哥

 2 years ago
source link: https://www.cnblogs.com/youyacoder/p/16554934.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在SpringBoot中配置 Druid 数据源及密码加密的方法

前文集成 MyBatis Plus,实现了一组增删改查接口。在启动服务时,从控制台中可以看出 Spring Boot 默认使用 Hikari 作为数据库连接池,Hikari性能很优秀。在国内使用较多的连接池还属阿里开源的 Druid,中文发音为德鲁伊Druid 结合了 C3P0、DBCP 等 DB 池的优点,同时还加入了日志监控,可以很好的监控 DB 池连接和 SQL 的执行情况。

1 集成 Druid

在 Spring Boot 中集成 Druid 可通过三种方式实现:

  1. 纯 yml 方式:在 yml 中配置连接池信息和druid 有关参数即可;
  2. Java Config 方式:编写配置类,在配置类中创建 druid 所需的实例,通过注解 @configuration 集成 Druid;
  3. 注解方式:通过 @WebServletWebFilter@ServletComponentScan等注解集成。

如果使用到多数据源,需要采用后面两种方式来配置。我们这个demo里面只有一个数据源,使用 yml 方式配置就行了。

1.1 添加依赖

Druid 与 Spring Boot 整合可以使用封装好的 starter: druid-spring-boot-starter。

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

1.2 配置 yml

在 application.yml 文件中,前面已经配置了数据源的驱动(driver-class-name)、连接地址(url)、用户名(username)、密码(password),现在需要追追加连接池类型配置、druid 连接池参数配置、druid 监控页面配置。

最后 spring.datasource 的配置如下:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/hero_springboot_demo?useUnicode=true&characterEncoding=utf8&useSSL=true
    username: root
    password: Mysql.123
    # 指定数据源为 DruidDataSource,默认值为 HikariDataSource
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 5
      min-idle: 5
      max-active: 5
      max-wait: 30000
      min-evictable-idle-time-millis: 30000
      time-between-eviction-runs-millis: 30000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 5
      filters: stat,wall
      use-global-data-source-stat: true
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        login-username: admin
        login-password: 111111
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: /druid/*, *.js, *.jpeg, *.jpg, *.png, *.gif, *.css
      filter:
        stat:
          merge-sql: true
          slow-sql-millis: 3000
          log-slow-sql: true

Druid 连接池配置的部分参数解析:

  1. initial-size:连接池初始化时创建的连接数量。
  2. min-idle:连接的最小空闲数量。
  3. max-active:最大活跃的连接数量。
  4. max-wait:等待超时时间。当遇到 DB 操作时,如果连接池中活跃的连接达到 max-active 就会等待,等待超过 max-wait 就会报错。
  5. min-evictable-idle-time-millis:连接允许的最大空闲时长(回收空闲连接的最小时长)
  6. time-between-eviction-runs-millis:多久检测一次连接池里连接的空闲时长
  7. validation-query:检测连接是否有效的 SQL
  8. filters:配置 druid 的扩展插件。stat - 用于监控统计的filter;wall - 用于预防 SQL 注入的filter。其他还有 log4j、config。
  9. filter:配置过滤器的参数:
    1. filter.stat.merge-sql:是否开启 mergeSQL的功能;
    2. filter.stat.slow-sql-millis:超过多久才是慢SQL
  10. stat-view-servlet 和 web-stat-filter 用于配置监控页面的 servlet 和 filter

想在浏览器中访问监控统计页面,stat-view-servlet.enabled 和 web-stat-filter.enable 都需要配置为 true。

配置完成后,在浏览器中访问:(前面已配置 stat-view-servlet.url-pattern 为 /druid/

http://localhost:9099/druid/

输入 stat-view-servlet 配置的 login-usernamelogin-password,进入 druid 的监控统计页面

image-20220728154326812

2 配置文件密码加密

在上面的数据源的配置中,数据库密码(spring.datasource.password)明文存储。在现实企业级开发中,通常采用配置中心的方式来解决。配置文件存储在配置中心上,而配置中心有权限控制,敏感环境(UAT、生产环境等)的配置文件只有特定人员或特定环境能够访问。但是如果无论什么环境,都对密码加密,是非常有必要的操作。

由于已经集成了 druid,可以使用 druid 提供的 ConfigTools 来进行加密,该类采用非对称方式加密。咱使用单元测试类来生成公钥、私钥、加密后的密码。新建一个单元测试类 com.yygnb.demo.ConfigToolsTest

package com.yygnb.demo;

import org.junit.Test;
import static com.alibaba.druid.filter.config.ConfigTools.encrypt;
import static com.alibaba.druid.filter.config.ConfigTools.genKeyPair;

public class ConfigToolsTest {

    @Test
    public void testPassword() throws Exception {
        String password = "Mysql.123";
        String[] arr = genKeyPair(512);
        System.out.println("privateKey:" + arr[0]);
        System.out.println("publicKey:" + arr[1]);
        System.out.println("password:" + encrypt(arr[0], password));
    }
}

将该方法中的变量 password 值替换成你自己的密码。执行该单元测试,会在控制台中分别输出私钥 privateKey、公钥publicKey 和加密后的密码 password:

image-20220728160243873
  1. 修改配置 spring.datasource.password ,值为上面的生成的加密后的密码
  2. 添加公钥配置 publicKey,值为上面生成的公钥
  3. 添加连接属性配置 spring.datasource.druid.connection-properties,值为:config.decrypt=true;config.decrypt.key=${publicKey}
  4. 启用配置 spring.datasource.druid.filter.config.enabled,值为 true
image-20220728161922985
image-20220728161949830

如果重启成功,则加密成功。此时如果将密码或公钥修改为错误的、或者 pring.datasource.druid.filter.config.enabled 设置 false,服务都会启动失败。

image

今日优雅哥(✔ youyacoder)学习结束,期待关注留言分享~~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK