HikariCP号称史上最快连接池,SpringBoot也已经采用HikariCP作为默认连接池,说明HikariCP的性能强。最关键的一点就是,HikariCP连接池不是使用的传统的ArrayList而是用的FastList。ArrayList操作get的时候,每次都要去检查一遍数组角标,而FastList却不需要去检查,类似的还有remove方法。
下面就是一个简单的实战小案例,帮助刚刚了解到HikariCp的朋友们,初步体验一下。
pom文件
<properties>
<hikari.version>2.6.1</hikari.version>
</properties>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${hikari.version}</version>
<scope>compile</scope>
</dependency>
配置文件 hirariCP.properties
hikariCP.driver=com.mysql.jdbc.Driver
hikariCP.url=jdbc:mysql:///test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
hikariCP.username=root
hikariCP.password=
hikariCP.cachePrepStmts=true
hikariCP.prepStmtCacheSize=250
hikariCP.prepStmtCacheSqlLimit=2048
bean
@Component
@PropertySource("classpath:hikariCP.properties")
public class HikariInfo {
@Value("${hikariCP.driver}")
private String driver;
@Value("${hikariCP.url}")
private String url;
@Value("${hikariCP.username}")
private String username;
@Value("${hikariCP.password}")
private String password;
@Value("${hikariCP.cachePrepStmts}")
private boolean cachePrepStmts;
@Value("${hikariCP.prepStmtCacheSize}")
private int prepStmtCacheSize;
@Value("${hikariCP.prepStmtCacheSqlLimit}")
private int prepStmtCacheSqlLimit;
public String getDriver() {
return driver;
}
public String getUrl() {
return url;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public boolean getCachePrepStmts() {
return cachePrepStmts;
}
public int getPrepStmtCacheSize() {
return prepStmtCacheSize;
}
public int getPrepStmtCacheSqlLimit() {
return prepStmtCacheSqlLimit;
}
}
配置连接池
@Configuration
public class HikariConfig {
@Resource
private HikariInfo hikariInfo;
@Bean
public HikariDataSource getDataSource(){
HikariDataSource hikariDataSource=new HikariDataSource();
hikariDataSource.setDriverClassName(hikariInfo.getDriver());
hikariDataSource.setJdbcUrl(hikariInfo.getUrl());
hikariDataSource.setUsername(hikariInfo.getUsername());
hikariDataSource.setPassword(hikariInfo.getPassword());
hikariDataSource.addDataSourceProperty("cachePrepStmts",hikariInfo.getCachePrepStmts());
hikariDataSource.addDataSourceProperty("prepStmtCacheSize",hikariInfo.getPrepStmtCacheSize());
hikariDataSource.addDataSourceProperty("prepStmtCacheSqlLimit",hikariInfo.getPrepStmtCacheSqlLimit());
return hikariDataSource;
}
@Bean
public JdbcTemplate getJdbcTemplate(HikariDataSource hikariDataSource){
return new JdbcTemplate(hikariDataSource);
}
}
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 根据id查找
* @param t_userId
* @return
*/
public User findByUserId(String t_userId){
String sql="SELECT * FROM t_user WHERE t_userId = ? ";
User user=null;
try {
user=jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),t_userId);
} catch (DataAccessException e) {
return null;
}
return user;
}