博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot2 集成三种连接池 c3p0 hikari druid
阅读量:6544 次
发布时间:2019-06-24

本文共 7641 字,大约阅读时间需要 25 分钟。

Hikari

1、首先集成 hikari springboot默认集成,只需要简单的配置即可

1.1 首先导入包

com.zaxxer
HikariCP
org.springframework.boot
spring-boot-starter-jdbc

1.2 编写配置文件

# hikari#spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot2#spring.datasource.username=root#spring.datasource.password=root#spring.datasource.driver-class-name=com.mysql.jdbc.Driver

1.3 编写配置类

package com.archibaldwitwicke.springboot2.chapter05.dao;import org.springframework.context.annotation.Configuration;@Configurationpublic class DataSourceConfiguration {    // Hikari 连接池//    @Bean(name = "dataSource")//    public DataSource dataSource(@Autowired Environment environment) {//        HikariDataSource ds = new HikariDataSource();//        ds.setJdbcUrl(environment.getProperty("spring.datasource.url"));//        ds.setUsername(environment.getProperty("spring.datasource.username"));//        ds.setPassword(environment.getProperty("spring.datasource.password"));//        ds.setDriverClassName(environment.getProperty("spring.datasource.driver-class-name"));//        return ds;//    }}

1.4 然后即可即可 jdbctemplate模板使用。

 

C3P0

1 导入相应包

c3p0
c3p0
0.9.1.2
org.springframework.boot
spring-boot-starter-jdbc

2 编写相应配置文件  

# c3p0#c3p0.jdbcUrl=jdbc:mysql://127.0.0.1:3306/springboot2#c3p0.user=root#c3p0.password=root#c3p0.driverClass=com.mysql.jdbc.Driver#c3p0.minPoolSize=2#c3p0.maxPoolSize=10#c3p0.maxIdleTime=1800000#c3p0.acquireIncrement=3#c3p0.maxStatements=1000#c3p0.initialPoolSize=3#c3p0.idleConnectionTestPeriod=60#c3p0.acquireRetryAttempts=30#c3p0.acquireRetryDelay=1000#c3p0.breakAfterAcquireFailure=false#c3p0.testConnectionOnCheckout=false

3 编写数据源类

package com.archibaldwitwicke.springboot2.chapter05.dao;import org.springframework.context.annotation.Configuration;@Configurationpublic class DataSourceConfiguration {    // c3p0 连接池//    @Bean(name = "dataSource")//    @Qualifier(value = "dataSource")//    @Primary//    @ConfigurationProperties(prefix = "c3p0")//    public DataSource dataSource(@Autowired Environment environment) {//        return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();//    }}

4 然后即可注入 jdbctemplate 操作数据库

 

Druid

1 导入相应包(需要日志包)

com.alibaba
druid
1.0.29
log4j
log4j
1.2.16
compile
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-jdbc

2 编写配置文件

# durid# 驱动配置信息spring.datasource.url = jdbc:mysql://127.0.0.1:3306/springboot2spring.datasource.username = rootspring.datasource.password = rootspring.datasource.driverClassName = com.mysql.jdbc.Driver#连接池的配置信息spring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=20spring.datasource.maxWait=60000spring.datasource.timeBetweenEvictionRunsMillis=60000spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT 1 FROM DUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=falsespring.datasource.poolPreparedStatements=truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20spring.datasource.filters=stat,wall,log4jspring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

还需要log4j配置:

log4j.rootCategory=INFO, stdoutlog4j.rootLogger=info, stdout### stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p - %m%n### set package ###log4j.logger.org.springframework=infolog4j.logger.org.apache.catalina=infolog4j.logger.org.apache.commons.digester.Digester=infolog4j.logger.org.apache.catalina.startup.TldConfig=infolog4j.logger.chb.test=debug

3 编写数据源类

package com.archibaldwitwicke.springboot2.chapter05.dao;import com.alibaba.druid.pool.DruidDataSource;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import javax.sql.DataSource;import java.sql.SQLException;@Configurationpublic class DruidDataSourceConfiguration {//    private Logger logger = LoggerFactory.getLogger(DruidDataSourceConfiguration.class);    @Value("${spring.datasource.url}")    private String dbUrl;    @Value("${spring.datasource.username}")    private String username;    @Value("${spring.datasource.password}")    private String password;    @Value("${spring.datasource.driverClassName}")    private String driverClassName;    @Value("${spring.datasource.initialSize}")    private int initialSize;    @Value("${spring.datasource.minIdle}")    private int minIdle;    @Value("${spring.datasource.maxActive}")    private int maxActive;    @Value("${spring.datasource.maxWait}")    private int maxWait;    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")    private int timeBetweenEvictionRunsMillis;    @Value("${spring.datasource.minEvictableIdleTimeMillis}")    private int minEvictableIdleTimeMillis;    @Value("${spring.datasource.validationQuery}")    private String validationQuery;    @Value("${spring.datasource.testWhileIdle}")    private boolean testWhileIdle;    @Value("${spring.datasource.testOnBorrow}")    private boolean testOnBorrow;    @Value("${spring.datasource.testOnReturn}")    private boolean testOnReturn;    @Value("${spring.datasource.poolPreparedStatements}")    private boolean poolPreparedStatements;    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")    private int maxPoolPreparedStatementPerConnectionSize;    @Value("${spring.datasource.filters}")    private String filters;    @Value("{spring.datasource.connectionProperties}")    private String connectionProperties;    @Bean     //声明其为Bean实例    @Primary  //在同样的DataSource中,首先使用被标注的DataSource    public DataSource dataSource() {        DruidDataSource datasource = new DruidDataSource();        datasource.setUrl(this.dbUrl);        datasource.setUsername(username);        datasource.setPassword(password);        datasource.setDriverClassName(driverClassName);        //configuration        datasource.setInitialSize(initialSize);        datasource.setMinIdle(minIdle);        datasource.setMaxActive(maxActive);        datasource.setMaxWait(maxWait);        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);        datasource.setValidationQuery(validationQuery);        datasource.setTestWhileIdle(testWhileIdle);        datasource.setTestOnBorrow(testOnBorrow);        datasource.setTestOnReturn(testOnReturn);        datasource.setPoolPreparedStatements(poolPreparedStatements);        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);        try {            datasource.setFilters(filters);        } catch (SQLException e) {//            logger.error("druid configuration initialization filter", e);            e.printStackTrace();        }        datasource.setConnectionProperties(connectionProperties);        return datasource;    }}

4 即可使用 jdbctemplate

 

以上所有数据源,根据需要导入数据驱动, 测试使用的为msyql

 

转载地址:http://teodo.baihongyu.com/

你可能感兴趣的文章
【树莓派】制作树莓派所使用的img镜像(一)
查看>>
理解网站并发量
查看>>
spring整合elasticsearch之环境搭建
查看>>
TensorFlow 架构与设计-编程模型【转】
查看>>
如何运行Struts2官网最新Demo?
查看>>
'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
查看>>
XDebug 教程
查看>>
js 去html 标签
查看>>
好久不见
查看>>
小tips:JS中的children和childNodes
查看>>
二叉树的遍历
查看>>
Oracle的FIXED_DATE参数
查看>>
PostgresSQL中的限制和级联删除
查看>>
NDK配置
查看>>
(转)@ContextConfiguration注解说明
查看>>
docker in centos error
查看>>
c# 线程同步: 详解lock,monitor,同步事件和等待句柄以及mutex
查看>>
[置顶] ※数据结构※→☆线性表结构(queue)☆============队列 顺序存储结构(queue sequence)(八)...
查看>>
Log4perl 的使用
查看>>
Linux 系统的单用户模式、修复模式、跨控制台登录在系统修复中的运用
查看>>