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

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

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

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

基本原理是这样的:

  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

相关文章

从原理到实战深入理解Java 断言assert

《从原理到实战深入理解Java断言assert》本文深入解析Java断言机制,涵盖语法、工作原理、启用方式及与异常的区别,推荐用于开发阶段的条件检查与状态验证,并强调生产环境应使用参数验证工具类替代... 目录深入理解 Java 断言(assert):从原理到实战引言:为什么需要断言?一、断言基础1.1 语

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

MySQL中的表连接原理分析

《MySQL中的表连接原理分析》:本文主要介绍MySQL中的表连接原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、环境3、表连接原理【1】驱动表和被驱动表【2】内连接【3】外连接【4编程】嵌套循环连接【5】join buffer4、总结1、背景

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实

Java 继承和多态的作用及好处

《Java继承和多态的作用及好处》文章讲解Java继承与多态的概念、语法及应用,继承通过extends复用父类成员,减少冗余;多态实现方法重写与向上转型,提升灵活性与代码复用性,动态绑定降低圈复杂度... 目录1. 继承1.1 什么是继承1.2 继承的作用和好处1.3 继承的语法1.4 子类访问父类里面的成

Java Stream的distinct去重原理分析

《JavaStream的distinct去重原理分析》Javastream中的distinct方法用于去除流中的重复元素,它返回一个包含过滤后唯一元素的新流,该方法会根据元素的hashcode和eq... 目录一、distinct 的基础用法与核心特性二、distinct 的底层实现原理1. 顺序流中的去重

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

SpringBoot 中 CommandLineRunner的作用示例详解

《SpringBoot中CommandLineRunner的作用示例详解》SpringBoot提供的一种简单的实现方案就是添加一个model并实现CommandLineRunner接口,实现功能的... 目录1、CommandLineRunnerSpringBoot中CommandLineRunner的作用