整合Druid数据源
# SpringBoot整合Druid数据源
Druid是一个关系型数据库连接池,它是阿里巴巴的一个开源项目。Druid支持所有JDBC兼容数据库,包括了Oracle、MySQL、PostgreSQL、SQL Server、H2等。 Druid在监控、可扩展性、稳定性和性能方面具有明显的优势。通过Druid提供的监控功能,可以实时观察数据库连接池和SQL查询的工作情况。使用Druid连接池在一定程度上可以提高数据访问效率。
# 1、application.yml和druidConfig.java配置Druid
# 步骤一:引入相关依赖
<!-- 核心启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 必须添加,否则会出现Error creating bean with name 'druidDataSource' -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!-- druid, 这里需要添加版本号 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
<!-- 数据库操作需要的mysql 驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- 使用druid监控页面需要是一个web项目, 引入web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 步骤二:application.yml中切换数据源
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.10.32:3306/jdbc
driver-class-name: com.mysql.jc.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
1
2
3
4
5
6
7
2
3
4
5
6
7
# 步骤三:application.yml中设置数据源相关配置
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.10.32:3306/jdbc
driver-class-name: com.mysql.jc.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#druid数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
#则导入log4j 依赖就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 步骤四:配置 DruidConfig
/**
* Created by baidou on 2021/2/26.
*
* class:DruidConfig
*/
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
//后台监控
@Bean
public ServletRegistrationBean statViewServlet() {
//注册 ServletBean
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//设置后台登录的账号密码
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername", "admin");
initParameters.put("loginPassword", "123456");
//允許谁能访问 initParameters.put("username","password");
bean.setInitParameters(initParameters);//初始化参数
return bean;
}
//Filter
public FilterRegistrationBean webStatFilter() {
//注册 FilterBean
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//可以过滤那些请求?
HashMap<String, String> initParameters = new HashMap<>();
//这些东西不进行统计
initParameters.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParameters);//初始化参数
return bean;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 步骤五:访问Druid监控
http://localhost:8000/druid/login.html
http://localhost:8000/druid/
1
2
2
# 2、application.yml配置Druid
# 步骤一:引入相关依赖
<!-- 核心启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 必须添加,否则会出现Error creating bean with name 'druidDataSource' -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!-- druid, 这里需要添加版本号 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
<!-- 数据库操作需要的mysql 驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- 使用druid监控页面需要是一个web项目, 引入web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 步骤二:application.yml中配置数据源
spring:
datasource:
druid:
# 数据源类型
db-type: com.alibaba.druid.pool.DruidDataSource
# 连接数据库的url,不同数据库不一样。例如:
# mysql : jdbc:mysql://ip:port/database
# oracle : jdbc:oracle:thin:@ip:port:database
url: jdbc:mysql://127.0.0.1:3306/joint_force?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 795200
# 驱动(根据url自动识别)这一项可配可不配,如果不配置druid会根据url自动识别dbType,然
# 后选择相应的driverClassName(建议配置下)
driver-class-name: com.mysql.cj.jdbc.Driver
# 始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时(缺省值:0)
initial-size: 2
# 最小连接池数量
min-idle: 5
# 最大连接池数量
max-active: 10
# 程序向连接池中请求连接时,超过maxWait的值后,认为本次请求失败,即连接池
max-wait: 5000
# 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。(缺省值:false)
# 默认是false
pool-prepared-statements: false
# 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。
# 在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100
max-open-prepared-statements: -1
# 每个连接最多缓存多少个SQL
max-pool-prepared-statement-per-connection-size: 20
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
max-evictable-idle-time-millis: 900000
# 用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。
validation-query: SELECT now()
# 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
test-while-idle: true
# 程序申请连接时,进行连接有效性检查(低效,影响性能)
test-on-borrow: false
# 程序返还连接时,进行连接有效性检查(低效,影响性能)
test-on-return: false
# 物理连接初始化的时候执行的sql
connection-init-sqls: SELECT now()
# 程序没有close连接且空闲时长超过 minEvictableIdleTimeMillis,则会执行validationQuery指定的SQL,以保证该程序连接不会池kill掉,其范围不超过minIdle指定的连接个数。
keep-alive: true
# 要求程序从池中get到连接后, N 秒后必须close,否则druid 会强制回收该false,当发现程序有未连接,不管该连接中是活动还是空闲, 以防止进程不会进行close而霸占连接。
remove-abandoned: true
# 当druid强制回收连接后,是否将stack trace 记录到日志中
log-abandoned: true
# 设置druid 强制回收连接的时限,当程序从池中get到连接开始算起,超过此值后,druid将强制回收该连接,单位秒。应大于业务运行最长时间
remove-abandoned-timeout: 6000
# 连接属性。比如设置一些连接池统计方面的配置。
connection-properties: druid.stat.mergeSql=true; druid.stat.slowSqlMillis=5000
# 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: 监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall
filters: stat, wall, slf4j
filter:
stat: # 监控统计
enabled: true
log-slow-sql: true # 慢SQL记录
slow-sql-millis: 1000 # 慢SQL执行时间
merge-sql: true # 是否合并sql
db-type: mysql # 数据库类型
wall: # 防御SQL注入
enabled: true
db-type: mysql
config:
delete-allow: false
drop-table-allow: false
multi-statement-allow: true
# statViewServlet配置
stat-view-servlet:
enabled: true # 是否启用
allow: 127.0.0.1 # 设置白名单,不填则允许所有访问
deny: 192.168.0.1 # 设置黑名单, 如果allow与deny同时存在,deny优先于allow
reset-enable: false # 禁止手动重置监控数据
url-pattern: /druid/*
login-username: admin # 设置监控页面的登陆密码
login-password: admin # 设置监控页面的登陆名
# WebStatFilter配置
web-stat-filter:
enabled: true # 是否启用
url-pattern: "/*" # 访问路径
exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*" # 排除不必要的url
session-stat-max-count: 1000 # 监控最大session数,默认是1000
session-stat-enable: true # 是否启用session的统计功能
profile-enable: true # 是否启用监控单个Url调用的sql列表
principalSessionName: session_user_key # 使druid当前session的用户是谁,session_user_key是你保存到session中的sessionName
principalCookieName: cookie_user_key # 使druid只当当前的user是谁,cookie_user_key是你保存在cookie中的cookieName
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# 步骤三:添加servlet支持
因druid监控页面是一个servlet,需要让SpingBoot支持servlet,所以在程序入口添加注解@ServletComponentScan,否则会出现404错误。
@SpringBootApplication
@ServletComponentScan
public class SingerwblogApplication {
public static void main(String[] args) {
SpringApplication.run(SingerwblogApplication.class, args);
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 步骤四:访问Druid监控
启动项目后,访问http://localhost:8080/druid/login.html,输入刚才配置文件配置的用户名和密码!
可以看到大致包含了如下几个模块:数据源、SQL监控、SQL防火墙、Web应用、URI监控、Session监控、JSONAPI等。
QL监控:可以查看所有的执行sql语句
SQL防火墙:druid提供了黑白名单的访问,可以清楚的看到sql防护情况。
Web应用:可以看到目前运行的web程序的详细信息。
URI监控:可以监控到所有的请求路径的请求次数、请求时间等其他参数。
Session监控:可以看到当前的session状况,创建时间、最后活跃时间、请求次数、请求时间等详细参数。
JSONAPI:通过api的形式访问Druid的监控接口,api接口返回Json形式数据。
编辑 (opens new window)