SpringBoot 集成 Druid
前言
JDK版本:1.8
Maven版本:3.8.1
操作系统:Win10
SpringBoot版本:2.3.12.RELEAS
- 当前 Springboot 版本选用
2.3.12.RELEASE
,关于版本的选择,这里先说明下,后续不在重复说明。 - 我日常微服务项目技术栈用到
Spring Cloud Alibaba
版本选用的是2.2.8.release
,而此版本对应的 SpringBoot 版本官方建议是2.3.12.RELEASE
,故Spring Boot系列项目也通用使用2.3.12.release
创建项目
File
=>New
=>Project
- 选择:Maven(注意:IDEA工具已经提前配置好了Maven、JDK等)
- 填写属性,这里主要更改了:Name、GroupId,最后点击
Finish
按钮即可。
由于junjiu-springboot-druid
已经创建完成,这里笔记时,故写成了jj-springboot-druid
后续笔记中使用的是junjiu-springboot-druid
(只是一个项目名字,问题不大)
项目创建完成之后,如下:
修改 pom.xml 文件
这里主要是引用包、版本等。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.3.12.RELEASE</version>
<relativePath />
</parent>
<groupId>com.junjiu.springboot.druid</groupId>
<artifactId>junjiu-springboot-druid</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<mysql.connector.java.version>8.0.28</mysql.connector.java.version>
<mybatis.plus.boot.starter.version>3.3.1</mybatis.plus.boot.starter.version>
<druid.version>1.2.13</druid.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MySQL驱动依赖. -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.java.version}</version>
</dependency>
<!-- mybatis-plus 依赖
https://baomidou.com/getting-started/
-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version> ${mybatis.plus.boot.starter.version} </version>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- lombok 依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
添加配置文件
在resources目录中创建application.yml
配置文件
配置文件内容如下:
# 端口
server:
port: 5826
spring:
application:
# 应用名称
name: junjiu-springboot-druid
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.88.54:3306/ideadb?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
username: fid_idea
password: 123456
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
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: 600000
validation-query: SELECT 1 FROM DUAL
# validation-query-timeout: 5000
test-on-borrow: false
test-on-return: false
test-while-idle: true
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#filters: #配置多个英文逗号分隔(统计,sql注入,log4j过滤)
filters: stat,wall
stat-view-servlet:
enabled: true
url-pattern: /druid/*
# 监控页面配置.
jj:
druid:
monitor:
login-username: root
login-password: 123456
reset-enable: false
开发 java 代码
当前项目的建设,主要两个原因:
- 研究
MySQL8.x
版本中的性能库performance_schema,例如:threads
、processlist
等视图。 - SpringBoot 项目集成 Druid,做个笔记。
项目中将可能缺少业务层、持久层等目录结构。
项目代码结构如下:
启动类 - DruidApplication
package com.junjiu.springboot.druid;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* program: junjiu-springboot-druid
* ClassName: DruidApplication
* description:
*
* @author: 君九
* @create: 2024-05-26 13:13
* @version: 1.0
**/
@SpringBootApplication
public class DruidApplication {
public static void main(String[] args) {
SpringApplication.run(DruidApplication.class);
}
}
配置文件-properties
DruidConfigProperty
package com.junjiu.springboot.druid.config.properties;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* program: junjiu-springboot-druid
* ClassName: DruidConfigProperty
* description:
*
* @author: 君九
* @create: 2024-05-26 13:19
* @version: 1.0
**/
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class DruidConfigProperty {
private String url;
private String username;
private String password;
private String driverClassName;
private int initialSize;
private int maxActive;
private int minIdle;
private int maxWait;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
private int timeBetweenEvictionRunsMillis;
private int minEvictableIdleTimeMillis;
private int maxEvictableIdleTimeMillis;
private String validationQuery;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private String filters;
private String connectionProperties;
}
DruidMonitorProperty
package com.junjiu.springboot.druid.config.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* program: junjiu-springboot-druid
* ClassName: DruidMonitorProperty
* description:
*
* @author: 君九
* @create: 2024-05-26 13:27
* @version: 1.0
**/
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "jj.druid.monitor")
public class DruidMonitorProperty {
private String loginUsername;
private String loginPassword;
private String resetEnable;
}
配置文件-config
DruidConfig
package com.junjiu.springboot.druid.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.junjiu.springboot.druid.config.properties.DruidConfigProperty;
import com.junjiu.springboot.druid.config.properties.DruidMonitorProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* program: junjiu-springboot-druid
* ClassName: DruidConfig
* description: Druid 配置文件
*
* @author: 君九
* @create: 2024-05-26 13:16
* @version: 1.0
**/
@Configuration
public class DruidConfig {
@Autowired
DruidConfigProperty druidConfigProperty;
@Autowired
DruidMonitorProperty druidMonitorProperty;
/**
* Druid 连接池配置
*/
@Bean
public DruidDataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(druidConfigProperty.getUrl());
datasource.setUsername(druidConfigProperty.getUsername());
datasource.setPassword(druidConfigProperty.getPassword());
datasource.setDriverClassName(druidConfigProperty.getDriverClassName());
datasource.setInitialSize(druidConfigProperty.getInitialSize());
datasource.setMinIdle(druidConfigProperty.getMinIdle());
datasource.setMaxActive(druidConfigProperty.getMaxActive());
datasource.setMaxWait(druidConfigProperty.getMaxWait());
datasource.setTimeBetweenEvictionRunsMillis(druidConfigProperty.getTimeBetweenEvictionRunsMillis());
datasource.setMinEvictableIdleTimeMillis(druidConfigProperty.getMinEvictableIdleTimeMillis());
datasource.setMaxEvictableIdleTimeMillis(druidConfigProperty.getMaxEvictableIdleTimeMillis());
datasource.setValidationQuery(druidConfigProperty.getValidationQuery());
datasource.setTestWhileIdle(druidConfigProperty.isTestWhileIdle());
datasource.setTestOnBorrow(druidConfigProperty.isTestOnBorrow());
datasource.setTestOnReturn(druidConfigProperty.isTestOnReturn());
datasource.setPoolPreparedStatements(druidConfigProperty.isPoolPreparedStatements());
datasource.setMaxPoolPreparedStatementPerConnectionSize(druidConfigProperty.getMaxPoolPreparedStatementPerConnectionSize());
try {
datasource.setFilters(druidConfigProperty.getFilters());
} catch (Exception ex) {
ex.printStackTrace();
}
datasource.setConnectionProperties(druidConfigProperty.getConnectionProperties());
return datasource;
}
/**
* JDBC操作配置
*/
@Bean
public JdbcTemplate jdbcTemplate (@Autowired DruidDataSource dataSource){
return new JdbcTemplate(dataSource) ;
}
/**
* 配置 Druid 监控界面
*/
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
//设置控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername",druidMonitorProperty.getLoginUsername());
servletRegistrationBean.addInitParameter("loginPassword",druidMonitorProperty.getLoginPassword());
// 是否可以重置数据
servletRegistrationBean.addInitParameter("resetEnable",druidMonitorProperty.getResetEnable());
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean statFilter(){
//创建过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//设置过滤器过滤路径
filterRegistrationBean.addUrlPatterns("/*");
//忽略过滤的形式
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
控制层
DruidController
package com.junjiu.springboot.druid.controller;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* program: junjiu-springboot-druid
* ClassName: DruidController
* description:
*
* @author: 君九
* @create: 2024-05-26 13:32
* @version: 1.0
**/
@RestController
public class DruidController {
@Resource
private JdbcTemplate jdbcTemplate;
@Autowired
private DruidDataSource druidDataSource;
/**
* 测试 Druid
* @return
*/
@GetMapping("/test")
public String testDruid() {
String sql = "select version()";
String result = jdbcTemplate.queryForObject(sql, String.class);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return "Success.".concat(simpleDateFormat.format(new Date())).concat(":").concat(result);
}
/**
* 测试连接池.
* 查看 performance_schema.threads 情况.
* @param size
* @return
*/
@GetMapping("/mutix/{size}")
public String testDruidMutix(@PathVariable("size") Integer size) {
for(int k = 0; k < size; k++) {
new Thread(() -> {
String sql = "select version()";
String result = jdbcTemplate.queryForObject(sql, String.class);
System.out.println(Thread.currentThread().getName() + ":" + result);
}).start();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return "Success.".concat(simpleDateFormat.format(new Date()));
}
}
运行
在 DruidApplication
类中,进行启动。
验证
Druid 的监控
在地址栏访问:http://localhost:5826/druid/
打开如下页面,输入配置中的账号、密码,即可访问。
应用程序
根据控制层代码访问路径,在浏览器地址栏中访问:
http://localhost:5826/test
,如下将会有返回。