Jdbc notes-database connection pool

Database connection pool

concept

When using basic Jdbc to operate, you must first apply for a Connection object every time you execute Sql, and then release it after execution, which consumes performance. So using the pooling technology, every time you access the database, a Connection object is taken out of the connection pool, and after the access is completed, the Connection object is returned to the connection pool. In order to achieve the purpose of reusing connection objects and reducing performance overhead.

benefit

  • Avoid frequent creation and destruction of Connection objects to improve performance

  • Convenient for unified management of Connection objects

achieve

  1. An interface DataSource is defined in the Jdbc standard. This interface is implemented by the driver supplier and has 3 implementations
    1. Basic realization: can generate standard Connection
    2. Connection pool implementation: can generate Connection that will automatically participate in the connection pool
    3. Distributed transaction implementation: Connection can be generated for distributed transactions
  2. If it is a DataSource implemented through a connection pool, the obtained Connection will be returned to the connection pool when it is closed, instead of closing the Connection

How to use connection pool

  1. Create DataSource object
  2. Call the DataSource getConnection()method to get the connection
  3. After the operation is completed, call the Connection's close method to return the connection (if a standard Connection, calling the close method will close the connection. For the Connection obtained through the database connection pool, calling the close method will not close the connection, but will return the connection)

Specific connection pool technology

c3p0

Steps for usage

  1. Import the jar package

    <!-- c3p0 -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.5</version>
    </dependency>
    
  2. Create a configuration file:

    By default, c3p0 will look for the c3p0.properties file or c3p0-config.xml file in the top directory of the classpath

    <?xml version="1.0" encoding="UTF-8"?>
    <c3p0-config>
    
        <!-- 可以配置多数据源,默认会加载default-config,也可以通过name来指定 -->
        <!-- 默认配置 -->
        <default-config>
            <!-- 连接四大参数配置 -->
            <!-- 对mysql8,若不指定serverTimezone,则c3p0会报错 -->
            <property name="jdbcUrl">jdbc:mysql:///yogurt?userSSL=false&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC&amp;autoReconnect=true</property>
            <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
            <property name="user">root</property>
            <property name="password">root</property>
            <!-- 池参数配置 -->
            <property name="initialPoolSize">5</property>
            <property name="maxPoolSize">10</property>
            <property name="checkoutTimeout">3000</property>
        </default-config>
    
        <!-- 其他库 -->
        <named-config name="other-config">
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/other</property>
            <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
            <property name="user">root</property>
            <property name="password">123</property>
            <property name="acquireIncrement">3</property>
            <property name="initialPoolSize">10</property>
            <property name="minPoolSize">2</property>
            <property name="maxPoolSize">10</property>
        </named-config>
    </c3p0-config>
    
  3. Create the core object CombPooledDataSource

  4. Get connection getConnection()

    Code example:

    @Test
    	public void testC3p0() throws SQLException {
          
          
    		//会使用默认配置
    		DataSource dataSource = new ComboPooledDataSource();
    		//下面会使用other-config这一项配置
    		//ComboPooledDataSource dataSource = new ComboPooledDataSource("other-config");
    		Connection connection = dataSource.getConnection();
    
    		Statement statement = connection.createStatement();
    		ResultSet set = statement.executeQuery("select * from user limit 3");
    		while (set.next()){
          
          
    			String name = set.getString("name");
    			System.out.println(name);
    		}
    		statement.close();
    		connection.close();
    	}
    
    @Test
    	public void testC3p0_2() throws SQLException {
          
          
    		DataSource dataSource = new ComboPooledDataSource();
    		//配置了最大连接数是10
    		for (int i = 0; i < 12; i++){
          
          
    			Connection connection = dataSource.getConnection();
    			System.out.println(i + ":" + connection);
    			if (i == 6 || i == 5){
          
          
    				//归还连接
    				//这样以来在超过10之后的2次也能获取到连接
    				connection.close();
    			}
    		}
    	}
    

druid

Steps for usage

  1. Import the jar package

    <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>druid</artifactId>
          <version>1.1.22</version>
     </dependency>
    
  2. Configuration file

    druid.properties

    The file name is arbitrary and can be placed in any directory, because druid will not be automatically loaded like c3p0, druid needs to manually load the configuration file

    db.url=jdbc:mysql://localhost:3306/yogurt?userSSL=false&characterEncoding=UTF-8&serverTimezone=UTC
    db.user=root
    db.password=root
    db.driverClass=com.mysql.cj.jdbc.Driver
    
  3. When getting the DataSource, use the factory class DruidDataSourceFactory

  4. Get Connection

Encapsulate druid, form a util, provide external

  • Get connection method
  • Release resource method
  • Get connection pool method
public class DruidUtil {
    
    
	private static DataSource dataSource;

	static {
    
    
		try {
    
    
			Properties properties = new Properties();
			properties.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
			dataSource = DruidDataSourceFactory.createDataSource(properties);
		}catch (Exception e){
    
    
			e.printStackTrace();
		}
	}

	//获取连接
	public static Connection getConnection() throws SQLException {
    
    
		//从连接池取出一个Connection
		return dataSource.getConnection();
	}

	//释放资源
	public static void close(Statement statement,Connection connection){
    
    
		close(null,statement,connection);
	}

	public static void close(ResultSet resultSet,Statement statement, Connection connection){
    
    

		if (resultSet != null){
    
    
			try {
    
    
				resultSet.close();
			} catch (SQLException e) {
    
    
				e.printStackTrace();
			}
		}

		if (statement != null){
    
    
			try {
    
    
				statement.close();
			} catch (SQLException e) {
    
    
				e.printStackTrace();
			}
		}

		if (connection != null){
    
    
			try {
    
    
				//归还连接
				connection.close();
			} catch (SQLException e) {
    
    
				e.printStackTrace();
			}
		}
	}

	//返回连接池
	public static DataSource getDataSource(){
    
    
		return dataSource;
	}
}

dbcp

slightly

Guess you like

Origin blog.csdn.net/vcj1009784814/article/details/106131718