连接池的作用就是为了提高性能,既然能提高性能还等啥,我们自己模拟编写一个连接池,探其究竟,明其原理。

本文主要是介绍连接池的作用就是为了提高性能,既然能提高性能还等啥,我们自己模拟编写一个连接池,探其究竟,明其原理。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

连接池的作用就是为了提高性能。

连接池的作用:连接池是将已经创建好的连接保存在池中,当有请求来时,直接使用已经创建好的连接对数据库进行访问。这样省略了创建连接和销毁连接的过程。这样性能上得到了提高。

基本原理是这样的:

  1. 建立数据库连接池对象(服务器启动)。
  2. 按照事先指定的参数创建初始数量的数据库连接(即:空闲连接数)。
  3. 对于一个数据库访问请求,直接从连接池中得到一个连接。如果数据库连接池对象中没有空闲的连接,且连接数没有达到最大(即:最大活跃连接数),创建一个新的数据库连接。
  4. 存取数据库。
  5. 关闭数据库,释放所有数据库连接(此时的关闭数据库连接,并非真正关闭,而是将其放入空闲队列中。如实际空闲连接数大于初始空闲连接数则释放连接)。
  6. 释放数据库连接池对象(服务器停止、维护期间,释放数据库连接池对象,并释放所有连接)。

连接池的概念和为什么要使用连接池?

连接池放了N个Connection对象,本质上放在内存当中,在内存中划出一块缓存对象,应用程序每次从池里获得Connection对象,而不是直接从数据里获得,这样不占用服务器的内存资源。

如果不使用连接池会出现的情况:

  • 占用服务器的内存资源
  • 导致服务器的速度非常慢

 既然,大家都了解了连接池的好处,那么我就动手写个固定大小的连接池,以方便伙伴们学习和交流。话不多说,直接上代码,走着~

package com.smallfan.connectionpool;import com.smallfan.TestVisiblity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicIntegerArray;/*** @PACKAGE_NAME: com.smallfan.connectionpool* @NAME: ConnectionPool* @USER: dell* @DATE: 2020/5/28* @PROJECT_NAME: aboutthread* 模拟实现固定大小的数据库连接池*/
public class TestPool{public static void main(String[] args) {//初始化连接池ConnectionPool pool = new ConnectionPool(2);for (int i = 0; i < 5; i++) {//创建5个线程争抢连接池new Thread(()->{Connection apply = pool.apply();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}pool.free(apply);}).start();}}
}
class ConnectionPool {static Logger logger = LoggerFactory.getLogger(ConnectionPool.class);//初始化连接池池大小private final int poolSize;//使用数组存储连接对象private Connection[] connections;//使用原子数组记录连接池状态 0:空闲 1:繁忙private AtomicIntegerArray status;//初始化public ConnectionPool(int poolSize) {this.poolSize = poolSize;this.connections = new Connection[poolSize];this.status = new AtomicIntegerArray(new int[poolSize]);for (int i = 0; i < poolSize; i++) {//初始化数据库连接connections[i] = new TestConnection("连接"+i);}}//申请连接public Connection apply(){while (true){for (int i = 0; i < poolSize; i++) {if(status.get(i) == 0){//是否存在空闲的连接if(status.compareAndSet(i,0,1)){//更新空闲连接为繁忙状态,保证原子操作并返回truelogger.info("获取连接 {}",connections[i]);return connections[i];}}}//若都是繁忙状态,阻塞synchronized (this){try {logger.info("等待连接");this.wait();} catch (InterruptedException e) {e.printStackTrace();}}}}//释放连接public void free(Connection connection){for (int i = 0; i < poolSize; i++) {if (connections[i] == connection){logger.info("释放连接{}",connections[i]);status.set(i,0);synchronized (this){this.notifyAll();}break;}}}}
//模拟实现Connection接口
class TestConnection implements Connection{String name;public TestConnection(String name) {this.name = name;}@Overridepublic String toString() {return "TestConnection{" +"name='" + name + '\'' +'}';}public Statement createStatement() throws SQLException {return null;}public PreparedStatement prepareStatement(String sql) throws SQLException {return null;}public CallableStatement prepareCall(String sql) throws SQLException {return null;}public String nativeSQL(String sql) throws SQLException {return null;}public void setAutoCommit(boolean autoCommit) throws SQLException {}public boolean getAutoCommit() throws SQLException {return false;}public void commit() throws SQLException {}public void rollback() throws SQLException {}public void close() throws SQLException {}public boolean isClosed() throws SQLException {return false;}public DatabaseMetaData getMetaData() throws SQLException {return null;}public void setReadOnly(boolean readOnly) throws SQLException {}public boolean isReadOnly() throws SQLException {return false;}public void setCatalog(String catalog) throws SQLException {}public String getCatalog() throws SQLException {return null;}public void setTransactionIsolation(int level) throws SQLException {}public int getTransactionIsolation() throws SQLException {return 0;}public SQLWarning getWarnings() throws SQLException {return null;}public void clearWarnings() throws SQLException {}public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {return null;}public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {return null;}public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {return null;}public Map<String, Class<?>> getTypeMap() throws SQLException {return null;}public void setTypeMap(Map<String, Class<?>> map) throws SQLException {}public void setHoldability(int holdability) throws SQLException {}public int getHoldability() throws SQLException {return 0;}public Savepoint setSavepoint() throws SQLException {return null;}public Savepoint setSavepoint(String name) throws SQLException {return null;}public void rollback(Savepoint savepoint) throws SQLException {}public void releaseSavepoint(Savepoint savepoint) throws SQLException {}public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {return null;}public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {return null;}public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {return null;}public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {return null;}public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {return null;}public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {return null;}public Clob createClob() throws SQLException {return null;}public Blob createBlob() throws SQLException {return null;}public NClob createNClob() throws SQLException {return null;}public SQLXML createSQLXML() throws SQLException {return null;}public boolean isValid(int timeout) throws SQLException {return false;}public void setClientInfo(String name, String value) throws SQLClientInfoException {}public void setClientInfo(Properties properties) throws SQLClientInfoException {}public String getClientInfo(String name) throws SQLException {return null;}public Properties getClientInfo() throws SQLException {return null;}public Array createArrayOf(String typeName, Object[] elements) throws SQLException {return null;}public Struct createStruct(String typeName, Object[] attributes) throws SQLException {return null;}public void setSchema(String schema) throws SQLException {}public String getSchema() throws SQLException {return null;}public void abort(Executor executor) throws SQLException {}public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {}public int getNetworkTimeout() throws SQLException {return 0;}public <T> T unwrap(Class<T> iface) throws SQLException {return null;}public boolean isWrapperFor(Class<?> iface) throws SQLException {return false;}
}

查看输出结果:

2020-05-28 23:37:18:687 [Thread-2] 等待连接
2020-05-28 23:37:18:689 [Thread-0] 获取连接 TestConnection{name='连接1'}
2020-05-28 23:37:18:689 [Thread-1] 获取连接 TestConnection{name='连接0'}
2020-05-28 23:37:18:716 [Thread-4] 等待连接
2020-05-28 23:37:18:716 [Thread-3] 等待连接
2020-05-28 23:37:19:717 [Thread-1] 释放连接TestConnection{name='连接0'}
2020-05-28 23:37:19:717 [Thread-0] 释放连接TestConnection{name='连接1'}
2020-05-28 23:37:19:718 [Thread-3] 获取连接 TestConnection{name='连接0'}
2020-05-28 23:37:19:718 [Thread-2] 等待连接
2020-05-28 23:37:19:718 [Thread-4] 获取连接 TestConnection{name='连接1'}
2020-05-28 23:37:20:732 [Thread-3] 释放连接TestConnection{name='连接0'}
2020-05-28 23:37:20:732 [Thread-2] 获取连接 TestConnection{name='连接0'}
2020-05-28 23:37:20:732 [Thread-4] 释放连接TestConnection{name='连接1'}
2020-05-28 23:37:21:732 [Thread-2] 释放连接TestConnection{name='连接0'}

 好像没有什么问题,欢迎伙伴们交流讨论,等你哦~

 

这篇关于连接池的作用就是为了提高性能,既然能提高性能还等啥,我们自己模拟编写一个连接池,探其究竟,明其原理。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1068895

相关文章

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

Tomcat高效部署与性能优化方式

《Tomcat高效部署与性能优化方式》本文介绍了如何高效部署Tomcat并进行性能优化,以确保Web应用的稳定运行和高效响应,高效部署包括环境准备、安装Tomcat、配置Tomcat、部署应用和启动T... 目录Tomcat高效部署与性能优化一、引言二、Tomcat高效部署三、Tomcat性能优化总结Tom

MySQL中的MVCC底层原理解读

《MySQL中的MVCC底层原理解读》本文详细介绍了MySQL中的多版本并发控制(MVCC)机制,包括版本链、ReadView以及在不同事务隔离级别下MVCC的工作原理,通过一个具体的示例演示了在可重... 目录简介ReadView版本链演示过程总结简介MVCC(Multi-Version Concurr

利用Python编写一个简单的聊天机器人

《利用Python编写一个简单的聊天机器人》这篇文章主要为大家详细介绍了如何利用Python编写一个简单的聊天机器人,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 使用 python 编写一个简单的聊天机器人可以从最基础的逻辑开始,然后逐步加入更复杂的功能。这里我们将先实现一个简单的

C#使用yield关键字实现提升迭代性能与效率

《C#使用yield关键字实现提升迭代性能与效率》yield关键字在C#中简化了数据迭代的方式,实现了按需生成数据,自动维护迭代状态,本文主要来聊聊如何使用yield关键字实现提升迭代性能与效率,感兴... 目录前言传统迭代和yield迭代方式对比yield延迟加载按需获取数据yield break显式示迭

Redis主从/哨兵机制原理分析

《Redis主从/哨兵机制原理分析》本文介绍了Redis的主从复制和哨兵机制,主从复制实现了数据的热备份和负载均衡,而哨兵机制可以监控Redis集群,实现自动故障转移,哨兵机制通过监控、下线、选举和故... 目录一、主从复制1.1 什么是主从复制1.2 主从复制的作用1.3 主从复制原理1.3.1 全量复制

Redis主从复制的原理分析

《Redis主从复制的原理分析》Redis主从复制通过将数据镜像到多个从节点,实现高可用性和扩展性,主从复制包括初次全量同步和增量同步两个阶段,为优化复制性能,可以采用AOF持久化、调整复制超时时间、... 目录Redis主从复制的原理主从复制概述配置主从复制数据同步过程复制一致性与延迟故障转移机制监控与维

使用PyQt5编写一个简单的取色器

《使用PyQt5编写一个简单的取色器》:本文主要介绍PyQt5搭建的一个取色器,一共写了两款应用,一款使用快捷键捕获鼠标附近图像的RGB和16进制颜色编码,一款跟随鼠标刷新图像的RGB和16... 目录取色器1取色器2PyQt5搭建的一个取色器,一共写了两款应用,一款使用快捷键捕获鼠标附近图像的RGB和16

SSID究竟是什么? WiFi网络名称及工作方式解析

《SSID究竟是什么?WiFi网络名称及工作方式解析》SID可以看作是无线网络的名称,类似于有线网络中的网络名称或者路由器的名称,在无线网络中,设备通过SSID来识别和连接到特定的无线网络... 当提到 Wi-Fi 网络时,就避不开「SSID」这个术语。简单来说,SSID 就是 Wi-Fi 网络的名称。比如

SpringCloud配置动态更新原理解析

《SpringCloud配置动态更新原理解析》在微服务架构的浩瀚星海中,服务配置的动态更新如同魔法一般,能够让应用在不重启的情况下,实时响应配置的变更,SpringCloud作为微服务架构中的佼佼者,... 目录一、SpringBoot、Cloud配置的读取二、SpringCloud配置动态刷新三、更新@R