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

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

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

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

基本原理是这样的:

  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

相关文章

基于Python编写一个git自动上传的脚本(打包成exe)

《基于Python编写一个git自动上传的脚本(打包成exe)》这篇文章主要为大家详细介绍了如何基于Python编写一个git自动上传的脚本并打包成exe,文中的示例代码讲解详细,感兴趣的小伙伴可以跟... 目录前言效果如下源码实现利用pyinstaller打包成exe利用ResourceHacker修改e

Java线程池核心参数原理及使用指南

《Java线程池核心参数原理及使用指南》本文详细介绍了Java线程池的基本概念、核心类、核心参数、工作原理、常见类型以及最佳实践,通过理解每个参数的含义和工作原理,可以更好地配置线程池,提高系统性能,... 目录一、线程池概述1.1 什么是线程池1.2 线程池的优势二、线程池核心类三、ThreadPoolE

MySQL日志UndoLog的作用

《MySQL日志UndoLog的作用》UndoLog是InnoDB用于事务回滚和MVCC的重要机制,本文主要介绍了MySQL日志UndoLog的作用,文中介绍的非常详细,对大家的学习或者工作具有一定的... 目录一、Undo Log 的作用二、Undo Log 的分类三、Undo Log 的存储四、Undo

C++ move 的作用详解及陷阱最佳实践

《C++move的作用详解及陷阱最佳实践》文章详细介绍了C++中的`std::move`函数的作用,包括为什么需要它、它的本质、典型使用场景、以及一些常见陷阱和最佳实践,感兴趣的朋友跟随小编一起看... 目录C++ move 的作用详解一、一句话总结二、为什么需要 move?C++98/03 的痛点⚡C++

Spring Boot Interceptor的原理、配置、顺序控制及与Filter的关键区别对比分析

《SpringBootInterceptor的原理、配置、顺序控制及与Filter的关键区别对比分析》本文主要介绍了SpringBoot中的拦截器(Interceptor)及其与过滤器(Filt... 目录前言一、核心功能二、拦截器的实现2.1 定义自定义拦截器2.2 注册拦截器三、多拦截器的执行顺序四、过

C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解

《C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解》:本文主要介绍C++,C#,Rust,Go,Java,Python,JavaScript性能对比全面... 目录编程语言性能对比、核心优势与最佳使用场景性能对比表格C++C#RustGoJavapythonjav

Java 队列Queue从原理到实战指南

《Java队列Queue从原理到实战指南》本文介绍了Java中队列(Queue)的底层实现、常见方法及其区别,通过LinkedList和ArrayDeque的实现,以及循环队列的概念,展示了如何高效... 目录一、队列的认识队列的底层与集合框架常见的队列方法插入元素方法对比(add和offer)移除元素方法

JAVA transient 关键字作用详解

《JAVAtransient关键字作用详解》Java的transient关键字用于修饰成员变量,使其不参与序列化过程,通过自定义序列化方法,可以手动控制transient变量的序列化行为,本文给大... 目录一、transient关键字作用二、原理详解三、典型使用场景四、代码示例五、注意事项六、与 stat

SQL 注入攻击(SQL Injection)原理、利用方式与防御策略深度解析

《SQL注入攻击(SQLInjection)原理、利用方式与防御策略深度解析》本文将从SQL注入的基本原理、攻击方式、常见利用手法,到企业级防御方案进行全面讲解,以帮助开发者和安全人员更系统地理解... 目录一、前言二、SQL 注入攻击的基本概念三、SQL 注入常见类型分析1. 基于错误回显的注入(Erro

Spring IOC核心原理详解与运用实战教程

《SpringIOC核心原理详解与运用实战教程》本文详细解析了SpringIOC容器的核心原理,包括BeanFactory体系、依赖注入机制、循环依赖解决和三级缓存机制,同时,介绍了SpringBo... 目录1. Spring IOC核心原理深度解析1.1 BeanFactory体系与内部结构1.1.1