目录
- 前言
- 一、数据库连接池?
- 1.1 HikariCP
- 1.2 Druid
- 二、Springboot整合Mybatis实操
- 2.1 目录结构
- 2.2 代码实现
- 三.开启Druid监控统计功能
- 3.1 监控页面及名词解释
- 3.2 去广告
- 总结
前言
使用Java程序操作数据库时,频繁的获得连接和关闭连接耗时会造成大量的性能开销增加系统响应时间。
连接池(根据配置创建和管理连接供需要的线程使用),使用者(Java程序)只需要调用连接,无需管理连接状态。
- 连接可复用
- 系统更快的响应速度
- 避免数据库资源泄露
一、数据库连接池?
1.1 HikariCP
在springboot2.0之后 , 采用的默认连接池就是Hikari, 号称"史上最快的连接池", 没有添加依赖也能直接用, springboot的自动配置中含有DataSourceAutoConfiguration配置类, 会先检查容器中是否已经有连接池对象, 没有则会使用默认的连接池, 并根据特定的属性来自动配置连接池对象, 用到的属性值来源于DataSourceProperties对象。
1.2 Druid
Druid 是一个 JDBC 组件库,包含数据库连接池、SQL Parser 等组件
相关配置文件的参数在 com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties org.springframework.boot.autoconfigure.jdbc.DataSourceProperties
二、Springboot整合Mybatis实操
2.1 目录结构
2.2 代码实现
在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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wudixiaofei</groupId>
<artifactId>springboot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-demo</name>
<description>springboot-demo</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 阿里巴巴的druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.23</version>
</dependency>
<!-- mysql8 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
<scope>runtime</scope>
</dependency>
<!-- mybatis引入了SpringBoot的JDBC模块,默认是使用 hikari作为数据源 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
<exclusions>
<!-- 排除默认的 HikariCP 数据源 -->
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=8080
spring.profiles.active=druid
#配置mapper
mybatis.mapper-locations=classpath:mapper/*.xml
#打印sql日志
logging.level.com.wudixiaofei.springbootdemo.mapper=debug
application-druid.yml
# 数据源配置
spring:
datasource:
url: jdbc:mysql://localhost:3366/springboot-demo?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource # 指定数据源类型
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
User.java
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserMapper.java
@Mapper
@Repository
public interface UserMapper {
//查询
List<User> queryAll();
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wudixiaofei.springbootdemo.mapper.UserMapper">
<select id="queryAll" resultType="com.wudixiaofei.springbootdemo.entity.User">
select * from sys_user
</select>
</mapper>
UserService.java
public interface UserService {
//查询
List<User> queryAll();
}
UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public List<User> queryAll() {
return userMapper.queryAll();
}
}
UserController.java
@Controller
public class UserController {
@Autowired
UserServiceImpl userServiceImpl;
@GetMapping("/getUser")
@ResponseBody
public List<User> getUser(){
return userServiceImpl.queryAll();
}
}
sys_user.sql
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Records of sys_user
-- ----------------------------
BEGIN;
INSERT INTO `sys_user` VALUES (1, 'root', '123');
INSERT INTO `sys_user` VALUES (2, 'admin', 'admin123');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
访问 http://localhost:8080/getUser
[{“username”:“root”,“password”:“123”},{“username”:“admin”,“password”:“admin123”}]
三.开启Druid监控统计功能
application-druid.yml 完整配置
# 数据源配置
spring:
datasource:
url: jdbc:mysql://localhost:3366/springboot-demo?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource # 指定数据源类型
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
# 应用向连接池申请连接,并且testOnBorrow为false时,连接池将会判断连接是否处于空闲状态,如果是,则验证这条连接是否可用
testWhileIdle: true
# 如果为true,默认是false,应用向连接池申请连接时,连接池会判断这条连接是否是可用的
testOnBorrow: false
# 如果为true(默认false),当应用使用完连接,连接池回收连接的时候会判断该连接是否还可用
testOnReturn: false
# 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle
poolPreparedStatements: true
# 要启用PSCache,必须配置大于0,当大于0时, poolPreparedStatements自动触发修改为true,
# 在Druid中,不会存在Oracle下PSCache占用内存过多的问题,
# 可以把这个数值配置大一些,比如说100
maxOpenPreparedStatements: 20
# 连接池中的minIdle数量以内的连接,空闲时间超过minEvictableIdleTimeMillis,则会执行keepAlive操作
keepAlive: true
# 开启Druid监控统计功能
webStatFilter: # webStatFilter过滤器:统计web应用请求中所有的数据库信息
enabled: true
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" # 排除一些不必要的url
session-stat-enable: true # 开启session统计功能
session-stat-max-count: 1000 # session的最大个数,默认100
statViewServlet:
enabled: true
# 设置白名单,不填则允许所有访问
allow:
# 访问内置监控页面的路径,内置监控页面的首页是/druid/index.html
url-pattern: /druid/*
# 控制台管理用户名和密码
login-username: root
login-password: 123456
filter:
stat:
enabled: true
# 慢SQL记录
log-slow-sql: true
db-type: mysql # 数据库的类型
slow-sql-millis: 1000 # 默认3000毫秒
merge-sql: true
wall:
config:
multi-statement-allow: true
# spring监控 需要导入AOP的Starter,配置多个英文逗号分隔
aop-patterns: "com.wudixiaofei.springbootdemo.mapper.*"
pom.xml 添加aop模块
<!--SpringBoot的aop模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
3.1 监控页面及名词解释
启动项目后,访问 http://localhost:8080/druid/login.html来到登录页面,输入配置好的用户名密码登录
名词解释:
- 数据源页面 是当前DataSource配置的基本信息
- SQL监控页面,统计了所有SQL语句的执行情况
- SQL防火墙页面, druid提供了黑白名单的访问,可以清楚的看到sql防护情况。
- Spring 监控页面,利用aop 对指定接口的执行时间,jdbc数进行记录
- URL监控页面,统计了所有Controller接口的访问以及执行情况
- Session监控页面,可以看到当前的session状况,创建时间、最后活跃时间、请求次数、请求时间等详细参数。
- JSONAPI 页面 ,通过api的形式访问Druid的监控接口,api接口返回Json形式数据。
3.2 去广告
监控页面的页脚有阿里的广告。如需去掉可以使用过滤器过滤。
注册一个过滤器,过滤common.js的请求,使用正则表达式替换相关的广告内容
package com.wudixiaofei.springbootdemo.filter;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import java.io.IOException;
@Configuration
@ConditionalOnWebApplication
@AutoConfigureAfter(DruidDataSourceAutoConfigure.class)
@ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled",
havingValue = "true", matchIfMissing = true)
public class RemoveDruidAdConfig {
/**
* 方法名: removeDruidAdFilterRegistrationBean
* 方法描述 除去页面底部的广告
* @param properties com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties
* @return org.springframework.boot.web.servlet.FilterRegistrationBean
*/
@Bean
public FilterRegistrationBean removeDruidAdFilterRegistrationBean(DruidStatProperties properties) {
// 获取web监控页面的参数
DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
// 提取common.js的配置路径
String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
final String filePath = "support/http/resources/js/common.js";
//创建filter进行过滤
Filter filter = new Filter() {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
// 重置缓冲区,响应头不会被重置
response.resetBuffer();
// 获取common.js
String text = Utils.readFromResource(filePath);
// 正则替换banner, 除去底部的广告信息
text = text.replaceAll("<a.*?banner\"></a><br/>", "");
text = text.replaceAll("powered.*?shrek.wang</a>", "");
response.getWriter().write(text);
}
@Override
public void destroy() {}
};
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(filter);
registrationBean.addUrlPatterns(commonJsPattern);
return registrationBean;
}
}
总结
本文主要想让读者了解引入连接池的意义、Mybatis的基本引入、介绍Druid的监控功能。