2019独角兽企业重金招聘Python工程师标准>>>
HikariCP号称性能最好的Java数据库连接池。虽没做过亲测但是公司项目一直在用,大概经历过2万左右用户同时在线,链接池性能方面未出现问题。
官网:http://brettwooldridge.github.io/HikariCP/
例子已上传码云:https://gitee.com/imlichao/HikariCP-example
安装
maven 坐标(这是java8的坐标,对应不同版本的jdk需要使用不同的版本)
<dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>2.7.6</version>
</dependency>
配置
增加HikariCP配置文件,设置连接池配置
package pub.lichao.test.config;import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;/*** HikariCP连接池配置*/
@Configuration
public class DataSourceConfig {@Value("${spring.datasource.url}")private String dataSourceUrl;@Value("${spring.datasource.username}")private String user;@Value("${spring.datasource.password}")private String password;@Beanpublic DataSource primaryDataSource() {HikariConfig config = new HikariConfig();config.setJdbcUrl(dataSourceUrl); //数据源config.setUsername(user); //用户名config.setPassword(password); //密码config.addDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置,为true时下面两个参数才生效config.addDataSourceProperty("prepStmtCacheSize", "250"); //连接池大小默认25,官方推荐250-500config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256,官方推荐2048config.addDataSourceProperty("useServerPrepStmts", "true"); //新版本MySQL支持服务器端准备,开启能够得到显著性能提升config.addDataSourceProperty("useLocalSessionState", "true");config.addDataSourceProperty("useLocalTransactionState", "true");config.addDataSourceProperty("rewriteBatchedStatements", "true");config.addDataSourceProperty("cacheResultSetMetadata", "true");config.addDataSourceProperty("cacheServerConfiguration", "true");config.addDataSourceProperty("elideSetAutoCommits", "true");config.addDataSourceProperty("maintainTimeStats", "false");HikariDataSource ds = new HikariDataSource(config);return ds;}
}
SpringBoot application.properties中配置数据源参数(具体参数含义请参考spring boot相关说明)
# Server HTTP port.
server.port=8090spring.datasource.url=jdbc:mysql://rdso30006c33s57oufvfo.mysql.rds.aliyuncs.com:3306/pltx-test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=*******
spring.datasource.password=*******
spring.datasource.driverClassName=com.mysql.jdbc.Driverspring.datasource.max-idle=10
spring.datasource.max-active=15
spring.datasource.max-lifetime=86430000
spring.datasource.log-abandoned=true
spring.datasource.remove-abandoned=true
spring.datasource.remove-abandoned-timeout=60
spring.datasource.initialize=false
spring.datasource.sqlScriptEncoding=UTF-8
连接数的确定可以参考:https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
启动项目我们可以看到项目使用了HikariCP连接池