HikariCP (Hikali) database connection pool part (default connection pool)
Introduction:
- HiKariCP (xi ka li)
- 1. HiKariCP is a rising star of the database connection pool. It claims to have the best performance and the fastest speed, and it can perfectly PK off other connection pools.
- 2. Hikari comes from Japanese and means "light" (the light of the sun, not the bare light) which means extremely fast
- 3. The slogan of this product is "Fast, Simple and Reliable"
- 4. Soon SpringBoot2.0 has adopted HikariCP as the default connection pool configuration
Comparison table of database connection pools
This PSCache is PreparedStatement Cache
SQL cache
Features | dbcp | druid | c3p0 | tomcat-jdbc | HikariCP |
---|---|---|---|---|---|
Whether to support PSCache | Yes | Yes | Yes | no | no |
monitor | jmx | jmx/log/http | jmx,log | jmx | jmx |
Scalability | weak | Great | weak | weak | weak |
SQL interception and analysis | no | stand by | no | no | no |
Code | simple | medium | complex | simple | simple |
Update time | 2015.8.6 | 2015.10.10 | 2015.12.09 | 2015.12.3 | |
Features | Depends on common-pool | Ali open source, full-featured | Long history, complex code logic, and difficult to maintain | Great optimization, simple functions, originated from boneCP | |
Connection pool management | LinkedBlockingDeque | Array | FairBlockingQue |
Just import spring-boot-starter-jdbc and rely on springboot to use HikariCP as the database connection pool by default.
application.yml configuration file
HikarICP configuration
datasource:
type: com.zaxxer.hikari.HikariDataSource #数据源的实现类
driverClassName: com.mysql.cj.jdbc.Driver #mysql驱动 8.0版本以上需要使用 com.mysql.cj.jdbc.Driver
url: jdbc:mysql://你的数据库地址:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root # 用户名
password: root # 密码
# Hikari 连接池配置
# 最小空闲连接数量
hikari:
minimum-idle: 5
# 空闲连接存活最大时间,默认600000(10分钟)
idle-timeout: 180000
# 连接池最大连接数,默认是10
maximum-pool-size: 10
# 此属性控制从池返回的连接的默认自动提交行为,默认值:true
auto-commit: true
# 连接池名称
pool-name: MyHikariCP
# 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
max-lifetime: 1800000
# 数据库连接超时时间,默认30秒,即30000
connection-timeout: 30000
connection-test-query: SELECT 1
Alibaba Druid connection pool
- Profile
Druid
is阿里巴巴
a database connection pool to achieve the open-source platform, combined with theC3P0
,DBCP
,PROXOOL
and otherDB
advantages of the pool, while addingLog monitoring。 - It can be said
Hikari
withDriud
all the current Java Web on the best data source HikariCP
Heavy speedDruid
heavy security and surveillance
Use Druid data source
- First import dependencies
<!--Druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
View project dependencies
- Go to application.yml to switch data source
- It has been said before that Spring Boot 2.0 and above use the com.zaxxer.hikari.HikariDataSource data source by default, but the data source can be specified by spring.datasource.type.
- After the replacement, you can go to the test directory to test whether the current data source below has been switched to the Druid data source
- Switched successfully! Now that the switch is successful, you can set the data source connection initialization size, maximum number of connections, waiting time, minimum number of connections and other settings;
- We can configure some parameters to test;
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://你的数据库地址:3306/smbms?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
username: root
password: root
# 更换数据源为Druid
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#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.Priority
#则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- Since the above configuration uses log4j, it is necessary to introduce the dependency of log4j, otherwise En...
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
- Now we need to own for the
com.alibaba.druid.pool.DruidDataSource
configuration parameter file binding global, adding it to the container, rather than usingSpring Boot
the automatic generation of; we need to addDruidDataSource
components to the container and binding properties; - Create Druid
配置类
config.DruidConfig
- Complete code
package com.yufire.springboot.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DruidConfig {
/*
将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
- OK Configuration is complete, let's test it
public class SpringbootDemoDataApplicationTests {
//注入数据源
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
//看一下默认数据源
System.out.println(dataSource.getClass());
//获得连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
DruidDataSource druidDataSource = (DruidDataSource) dataSource;
System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());
System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize());
//关闭连接
connection.close();
}
}
Configure Druid
Data Source MonitoringHighlight
- Druid data source has the monitoring function, and provides a web interface for users to view, similar to when the router is installed, others also provide a default web page.
- So the first step is to set up Druid's back-end management page, such as login account, password, etc.; configure back-end management;
Add the following code to the Druid configuration you just created
/**
* 配置 Druid 监控管理后台的Servlet;
* 内置 Servler 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
* @return
*/
@Bean
public ServletRegistrationBean statViewServlet() {
//配置Durid管理界面访问地址
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParams = new HashMap<>();
//后台管理界面的登录账号 initParams初始化配置需要的key都是死配置并且不能写错
initParams.put("loginUsername", "admin");
//后台管理界面的登录密码
initParams.put("loginPassword", "123456");
//后台允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
//initParams.put("allow", ""):为空或者为null时,表示允许所有访问
initParams.put("allow", "");
//deny:Druid 后台拒绝谁访问
//initParams.put("yufire", "192.168.1.20");表示禁止此ip访问
//设置初始化参数
bean.setInitParameters(initParams);
return bean;
//这些参数可以在 com.alibaba.druid.support.http.StatViewServlet 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
}
/**
* 配置 Druid 监控 之 web 监控的 filter
* WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
* @return
*/
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
//"/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
- After configuration, we can choose to visit: http://localhost:8080/druid/login.html
After successfully logging in, you will see the following page
After the integration, you can use the persistence layer framework ( MyBatis-Plus
tk.mybatis
etc.) to play happily~~~
This article is not authorized to reprint! Editing is not easy, please indicate the source for forwarding! Author qq: 2867874665