首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring配置连接池

spring配置连接池

作者头像
逍遥壮士
发布2020-09-18 11:39:04
1.5K0
发布2020-09-18 11:39:04
举报
文章被收录于专栏:技术趋势技术趋势

连接池是什么?

数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。这项技术能明显提高对数据库操作的性能。

个人理解:就是类似于水库,你每次都要跑老远去取水,这样很麻烦,于是人们建立一个水库,你想要水的时候可以直接从里面取,如果水库水少了,你又可以其他渠道把水导进去,做储蓄,等到要的时候直接取就可以了。

参考文章:https://baike.baidu.com/item/%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0

为什么要使用连接池?

连接池可以很多的减少数据库的开销,不用每次都去创建一个连接,然后再关闭,因为建立数据库的连接是一个非常耗时、消耗系统资源的行为,而是由连接池直接为你直接创建好,维持一定的连接数,当你需要的直接从连接池为你分配一个,减少了创建开销和提升安全性,并且通过连接池来维护,整体来说对整个性能也提升了,还在一定程度上节省了资源和时间。

spring有哪些数据连接池?

spring jdbc:

严格来说这 spring-jdbc不能算是一个连接池,因为该功能是spring提供的一个简单的jdbc连接,当连接到时达一定量后会出现异常。一般非常少用。可以参考:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/DriverManagerDataSource.html

https://blog.csdn.net/zhuqiuhui/article/details/70307052

c3p0:

开源的JDBC连接池,实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate、Spring等。单线程,性能较差,适用于小型系统,代码600KB左右。参考:https://baike.baidu.com/item/c3p0

jndi:

是一种规范,具体非常少用,可以参考:https://blog.csdn.net/kingmax54212008/article/details/52229642

druid:

Druid连接池是开源的数据库连接池项目。Druid连接池为监控而生,内置强大的监控功能,监控特性不影响性能。功能强大,能防SQL注入,内置Loging能诊断Hack应用行为。使用得非常频繁,而且性能也是杠杠的...

HikariCP:

HikariCP是一个高性能的JDBC连接池,基于BoneCP做了不少的改进和优化。作者是个日本人,他还有另外一个开源作品——高性能的JSON解析器HikariJSON。国外号称性能最好的连接池,国内很少人用。

参考https://github.com/alibaba/druid/wiki/Druid%E8%BF%9E%E6%8E%A5%E6%B1%A0%E4%BB%8B%E7%BB%8D

https://github.com/brettwooldridge/HikariCP

https://blog.csdn.net/hetaohappy/article/details/84759868

https://github.com/brettwooldridge/HikariCP

spring相关的数据源配置

代码下载:https://gitee.com/hong99/spring/issues/I1N1DF

代码实现

dbcp配置

相关配置参考:http://commons.apache.org/proper/commons-dbcp/configuration.html

java代码实现

applicatonContext-datasource.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:p="http://www.springframework.org/schema/p"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

   <context:component-scan base-package="com.hong.spring.datasource"/>
</beans>
/**
 * @Auther: csh
 * @Date: 2020/8/13 11:44
 * @Description:java实现dbcp的配置
 */
@Configuration
public class DbcpConfig {
    /**
     *
     * 功能描述:通过代码实现
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/13 14:26
     */
    @Bean
    public DataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8");
        ds.setUsername("root");
        ds.setPassword("123456");
        return ds;
    }
}
/**
 * @Auther: csh
 * @Date: 2020/8/13 11:42
 * @Description:测试各种数据源
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:datasource/applicatonContext-datasource.xml")
public class DataSourceTest {

    @Autowired
    DbcpConfig dbcpConfig;
    /**
     *
     * 功能描述:通过java代码实现dbcp
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/13 11:46
     */
    @Test
    public void javaDbcpTest() throws SQLException {
        DataSource dataSource = dbcpConfig.dataSource();
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
}

结果

jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8, UserName=root@localhost, MySQL Connector Java

xml实现

的xml新增

<!--xml配置dbcp-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--destroy-method代码当spring关闭时,数据源也会自动跟着关闭-->
<!--p:driverClassName 驱动的类名称-->
<!--p:url 数据库连接地址-->
<!--p:username 数据库登陆账号-->
<!--p:password 数据库登陆密码-->
<!--p:defaultAutoCommit 设置数据源返回连接是否采用自动提交机制 默认是true-->
<!--p:defaultReadOnly="false" 设置数据是否只读,默认是false-->
<!--p:defaultTransactionIsolation="" 设置数据源的默认事务级别 默认是不配的。-->
<!--p:initialSize="50" 初始化连接池的连接数-->
<!--p:maxActive="50" 最大连接数据库连接数,设置为0时,表示没有限制-->
<!--p:maxIdle="50" 最大等待连接中的数量,设置为0时,表示没有限制-->
<!--p:maxWait="50" 最大等待秒数,单位为毫秒, 超过时间会报出错误信息;-->
<!--p:removeAbandoned="false" 是否自我中断,默认是 false -->
<!--p:removeAbandoned="false" 是否自我中断,默认是 false -->
<!--p:removeAbandonedTimeout="5" 几秒后数据连接会自动断开,在removeAbandoned为true,提供该值 -->
<!--p:logAbandoned="false" 是否记录中断事件, 默认为 false -->
<!--更多参考:http://commons.apache.org/proper/commons-dbcp/configuration.html-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close"
     p:driverClassName="${jdbc.driver}"
     p:url="${jdbc.url}"
     p:username="${jdbc.user}"
     p:password="${jdbc.password}"
     p:defaultAutoCommit="true"
     p:defaultReadOnly="false"
     p:initialSize="50"
     p:maxActive="5000"
     p:maxIdle="50"
     p:maxWait="50"
     p:removeAbandoned="false"
     p:removeAbandonedTimeout="5"
     p:logAbandoned="false"
/>

在DataSourceTest中新增

/**
 *
 * 功能描述:通过xml实现dbcp数据源
 *
 * @param:
 * @return:
 * @auther: csh
 * @date: 2020/8/13 15:44
 */
@Test
public void xmlDbcpTest() throws SQLException {
    Connection connection = dataSource.getConnection();
    System.out.println("xml获取结果:"+connection);
}

结果

xml获取结果:jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8, UserName=root@localhost, MySQL Connector Java

jndi配置

引入jar包

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-util</artifactId>
    <version>3.4.2</version>
</dependency>

<dependency>
    <groupId>jboss</groupId>
    <artifactId>jbossall-client</artifactId>
    <version>3.2.6</version>
</dependency>

xml配置实现代码实现

package com.hong.spring.datasource.config;

import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.SharedPoolDataSource;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;

import javax.naming.NamingException;

public class JndiBean {

    public JndiBean() {
        try {
            DriverAdapterCPDS cpds = new DriverAdapterCPDS();
            cpds.setDriver("com.mysql.jdbc.Driver");
            cpds.setUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8");
            cpds.setUser("root");
            cpds.setPassword("123456");
 
            SharedPoolDataSource dataSource = new SharedPoolDataSource();
            dataSource.setConnectionPoolDataSource(cpds);
            dataSource.setMaxActive(10);
            dataSource.setMaxWait(50);
 
            SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
            builder.bind("java:comp/env/jdbc/hong", dataSource);
            builder.activate();
        } catch (NamingException | ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }
}

META-INF/context.xml 关于如何配META-INF参照:https://blog.csdn.net/Fan_JiGang/article/details/86759179

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/">
    <Resource name="jdbc/jndi"
              auth="Container"
              type="javax.sql.DataSource"
              factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
              maxActive="20"
              maxIdel="10"
              maxWait="1000"
              driverClassName="com.mysql.jdbc.Driver"
              username="root"
              password="123456"
              url="jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&amp;generateSimpleParameterMetadata=true"/>
</Context>

datasource/applicatonContext-jndi.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

   <!--扫包-->
   <context:component-scan base-package="com.hong.spring.datasource"/>

   <bean id="jndi" class="com.hong.spring.datasource.config.JndiBean" lazy-init="false" />

   <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="java:comp/env/jdbc/hong"/>
      <property name="resourceRef" value="true" />
   </bean>
</beans>

结果

jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8, UserName=root@localhost, MySQL Connector Java

c3p0实现

maven包

<!-- 整合c3p0连接池 -->
<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>

java代码实现

c3p0.properties

config.properties:
#数据库驱动
jdbc.driver=com.mysql.jdbc.Driver
#数据库连接url
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
#数据库用户名
jdbc.user=root
#数据库密码
jdbc.password=123456

com.hong.spring.datasource.config.C3p0Config

package com.hong.spring.datasource.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
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 org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Auther: csh
 * @Date: 2020/8/13 18:12
 * @Description:配置cp30
 */
@Configuration
@PropertySource("c3p0.properties")
public class C3p0Config {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.user}")
    private String user;

    @Value("${jdbc.password}")
    private String password;

    //添加@Primary防止跟xml里面注册的连接池冲突
    @Primary
    @Bean
    public DataSource init() throws PropertyVetoException, SQLException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setPassword(password);
        dataSource.setUser(user);
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        return dataSource;
    }
}

datasource/applicatonContext-c3p0.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:p="http://www.springframework.org/schema/p"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
   <!--扫包-->
   <context:component-scan base-package="com.hong.spring.datasource"/>
   <!--加载c3p0的配置-->
   <context:property-placeholder location="classpath:c3p0.properties"/>
</beans>
package datasource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Auther: csh
 * @Date: 2020/8/13 11:42
 * @Description:测试c3p0连接池
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:datasource/applicatonContext-c3p0.xml")
public class C3p0DataSourceTest {

    @Autowired
    private ComboPooledDataSource dataSource;

    @Autowired
    private DataSource init;

    /**
     *
     * 功能描述:java代码实现
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/13 18:30
     */
    @Test
    public void javaTestC3p0() throws SQLException {
        Connection connection = init.getConnection();
        System.out.println(connection);
    }
    
}

结果

com.mchange.v2.c3p0.impl.NewProxyConnection@1e683a3e

xml实现

datasource/applicatonContext-c3p0.xml 添加如下:

<!-- 整合c3p0连接池 name的第一个字母可以大写也可以小写 -->
<bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
   <!--数据驱动-->
   <property name="driverClass" value="${jdbc.driver}"></property>
   <!--数据库地址-->
   <property name="jdbcUrl" value="${jdbc.url}"></property>
   <!--数据库用户名-->
   <property name="user" value="${jdbc.user}"></property>
   <!--数据库密码-->
   <property name="password" value="${jdbc.password}"></property>
</bean>

datasource.C3p0DataSourceTest 添加如下

/**
 *
 * 功能描述:xml测试jndi
 *
 * @param:
 * @return:
 * @auther: csh
 * @date: 2020/8/13 17:41
 */
@Test
public void xmlTestC3p0() throws SQLException {
    Connection connection = dataSource.getConnection();
    System.out.println(connection);
}

结果

com.mchange.v2.c3p0.impl.NewProxyConnection@1e683a3e

druid配置

maven

<!--引入连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>

xml配置

jdbc.properties

config.properties:
#数据库驱动
jdbc.driver=com.mysql.jdbc.Driver
#数据库连接url
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
#数据库用户名
jdbc.user=root
#数据库密码
jdbc.password=123456

datasource/applicatonContext-druid.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

   <!--扫包-->
   <!--<context:component-scan base-package="com.hong.spring.datasource"/>-->
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:jdbc.properties"/>


   <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
      <!-- 基础配置 -->
      <property name="url" value="${jdbc.url}"></property>
      <property name="driverClassName" value="${jdbc.driver}"></property>
      <property name="username" value="${jdbc.user}"></property>
      <property name="password" value="${jdbc.password}"></property>

      <!-- 关键配置 -->
      <!-- 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 -->
      <property name="initialSize" value="3" />
      <!-- 最小连接池数量 -->
      <property name="minIdle" value="2" />
      <!-- 最大连接池数量 -->
      <property name="maxActive" value="15" />
      <!-- 配置获取连接等待超时的时间 -->
      <property name="maxWait" value="10000" />

      <!-- 性能配置 -->
      <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
      <property name="poolPreparedStatements" value="true" />
      <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

      <!-- 其他配置 -->
      <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
      <property name="timeBetweenEvictionRunsMillis" value="60000" />
      <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
      <property name="minEvictableIdleTimeMillis" value="300000" />
      <!--   建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,
                  执行validationQuery检测连接是否有效。-->
      <property name="testWhileIdle" value="true" />
      <!-- 这里建议配置为TRUE,防止取到的连接不可用 ,申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。-->
      <property name="testOnBorrow" value="true" />
      <!-- 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 -->
      <property name="testOnReturn" value="false" />
   </bean>
</beans>

datasource.DruidDataSourceTest

package datasource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @Auther: csh
 * @Date: 2020/8/13 11:42
 * @Description:测试druid连接池
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:datasource/applicatonContext-druid.xml")
public class DruidDataSourceTest {

    @Autowired
    private DataSource dataSource;


    /**
     *
     * 功能描述:xml测试druid
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/13 17:41
     */
    @Test
    public void xmlTestDruid() throws SQLException {
        System.out.println(dataSource.getConnection());
    }
}

结果

com.mysql.jdbc.JDBC4Connection@479ceda0

jdbc配置

jdbc.properties

config.properties:
#数据库驱动
jdbc.driver=com.mysql.jdbc.Driver
#数据库连接url
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
#数据库用户名
jdbc.user=root
#数据库密码
jdbc.password=123456

maven包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.11.RELEASE</version>
</dependency>

java实现

datasource.JdbcDataSourceTest

package datasource;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 *
 * 功能描述:测试jdbc连接池
 *
 * @param:
 * @return:
 * @auther: csh
 * @date: 2020/8/14 9:45
 */
public class JdbcDataSourceTest {

    /**
     *
     * 功能描述:java代码获取jdbc
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/14 9:59
     */
    @Test
    public void javaJdbc() throws PropertyVetoException, SQLException {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
}

结果

com.mysql.jdbc.JDBC4Connection@4de8b406

xml实现

datasource/applicatonContext-jdbc.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

   <!--扫包-->
   <!--<context:component-scan base-package="com.hong.spring.datasource"/>-->
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:jdbc.properties"/>


   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <!-- 基础配置 -->
      <property name="url" value="${jdbc.url}"></property>
      <property name="driverClassName" value="${jdbc.driver}"></property>
      <property name="username" value="${jdbc.user}"></property>
      <property name="password" value="${jdbc.password}"></property>
   </bean>
</beans>

在单元测试 datasource.JdbcDataSourceTest 添加如下

/**
 *
 * 功能描述:xml获取jdbc
 *
 * @param:
 * @return:
 * @auther: csh
 * @date: 2020/8/14 9:59
 */
@Test
public void xmlJdbc() throws SQLException {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("datasource/applicatonContext-jdbc.xml");
    DriverManagerDataSource bean = applicationContext.getBean(DriverManagerDataSource.class);
    System.out.println(bean.getConnection());
}

结果

com.mysql.jdbc.JDBC4Connection@240237d2

HikariCP配置

maven

<!-- 整合HikariCP -->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>3.4.1</version>
</dependency>

java实现

package datasource;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Auther: csh
 * @Date: 2020/8/13 11:42
 * @Description:测试HikariCP连接池
 */
public class HikariCPDataSourceTest {
    private static HikariConfig config = new HikariConfig();
    private static HikariDataSource ds;

    static {
        config.setJdbcUrl( "jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8" );
        config.setUsername( "root" );
        config.setPassword( "123456" );
        config.addDataSourceProperty( "cachePrepStmts" , "true" );
        config.addDataSourceProperty( "prepStmtCacheSize" , "250" );
        config.addDataSourceProperty( "prepStmtCacheSqlLimit" , "2048" );
        ds = new HikariDataSource( config );
    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    /**
     *
     * 功能描述:通过java配置
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/8/14 16:06
     */
    @Test
    public void javaHikariCPTest() throws SQLException {
        Connection connection = getConnection();
        System.out.println(connection);
    }

}

结果

HikariProxyConnection@1454127753 wrapping com.mysql.jdbc.JDBC4Connection@27c20538

xml实现

datasource/applicatonContext-hikari.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

   <!--扫包-->
   <!--<context:component-scan base-package="com.hong.spring.datasource"/>-->
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:jdbc.properties"/>

   <context:property-placeholder location="jdbc.properties"></context:property-placeholder>
   <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
      <property name="driverClassName" value="${jdbc.driver}"></property>
      <property name="jdbcUrl" value="${jdbc.url}"></property>
      <property name="username" value="${jdbc.user}"></property>
      <property name="password" value="${jdbc.password}"></property>
      <!--是否为只读数据库-->
      <property name="readOnly" value="false"></property>
      <!--等待连接池分配链接的最大时长-->
      <property name="connectionTimeout" value="30000"></property>
      <!--一个链接idle状态最大时长-->
      <property name="idleTimeout" value="600000"></property>
      <!--一个链接最长的生命时长,超时没有被使用则被释放掉 简易比数据库超时时长少 30s-->
      <property name="maxLifetime" value="1800000"></property>
      <!--连接池允许的最大连接数-->
      <property name="maximumPoolSize" value="20"></property>
   </bean>
</beans>

在datasource.HikariCPDataSourceTest 中添加如下

/**
 *
 * 功能描述:xml获取jdbc
 *
 * @param:
 * @return:
 * @auther: csh
 * @date: 2020/8/14 9:59
 */
@Test
public void xmlJdbc() throws SQLException {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("datasource/applicatonContext-jdbc.xml");
    DriverManagerDataSource bean = applicationContext.getBean(DriverManagerDataSource.class);
    System.out.println(bean.getConnection());
}

结果

HikariProxyConnection@919112242 wrapping com.mysql.jdbc.JDBC4Connection@7880cdf3

代码下载:https://gitee.com/hong99/spring/issues/I1N1DF

参考文章:

https://blog.csdn.net/liu1390910/article/details/97929972

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-08-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 技术趋势 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码下载:https://gitee.com/hong99/spring/issues/I1N1DF
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档