java自定义连接池
1、java自定义连接池
1.1连接池的概念:
实际开发中"获取连接"或“释放资源”是非常消耗系统资源的两个过程,为了姐姐此类性能问题,通常情况我们采用连接池技术来贡献连接Connection
用池来管理Connection,这样可以重复使用Connection,有了池,所以我们就不用自己来创建Connection,而是通过池来获取Connection对象,当使用完Connection后,调用Connection的close()方法也不会真的关闭Connection,而是把Connection“归还”给池,池也就可以再利用这个Connection对象啦
1.2 自定义连接池需要如下步骤
1.2.1 创建连接池实现(数据源),并实现接口javax.sql.DataSource.简化本案案例,我们可以自己提供方法,没有实现接口
1.2.2 提供一个集合,用于存放连接,因为移除/添加操作过多,所以选用LinkedList较好
1.2.3 为连接池初始化5个连接
1.2.4 程序如果需要连接,调用实现类的getConnection(),本方法姜葱连接池(容器List)获取连接,为了保证当前连接只是停工给一个线程使用,我们需要将连接先从连接池冲移除。
1.2.5 当用户使用完连接,释放资源时,不执行close()方法,而是将连接添加到连接池中
代码实现:
package com.rookie.bigdata.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
/**
* @author
* @date 2019/1/13
*/
public class JDBCUtils {
private static String driver;
private static String url;
private static String username;
private static String password;
/**
* 静态代码块加载配置文件信息
*/
static {
try {
// 1.通过当前类获取类加载器
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
// 2.通过类加载器的方法获得一个输入流
InputStream is = classLoader.getResourceAsStream("db.properties");
// 3.创建一个properties对象
Properties props = new Properties();
// 4.加载输入流
props.load(is);
// 5.获取相关参数的值
driver = props.getProperty("driver");
url = props.getProperty("url");
username = props.getProperty("username");
password = props.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取连接方法
*
* @return
*/
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 释放资源方法
*
* @param conn
* @param pstmt
* @param rs
*/
public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package com.rookie.bigdata.datasource;
import com.rookie.bigdata.utils.JDBCUtils;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;
/**
* @author liuxili
* @date 2019/1/13
*/
public class MyDataSource implements DataSource {
//创建一个容器,用于存放connection对象
private static LinkedList<Connection> pool = new LinkedList<>();
//初始化5个连接,放到容器中
static {
for (int i = 0; i < 5; i++) {
Connection connection = JDBCUtils.getConnection();
pool.add(connection);
}
}
/**
* 获取连接的方法
*
* @return
* @throws SQLException
*/
@Override
public Connection getConnection() throws SQLException {
//当连接池中没有连接的时候,需要创建链接
if (pool.size() == 0) {
for (int i = 0; i < 5; i++) {
Connection connection = JDBCUtils.getConnection();
pool.add(connection);
}
}
//从池中获取连接
return pool.remove(0);
}
/**
* 归还连接到连接池中
*
* @param connection
*/
public void releaseConnetion(Connection connection) {
pool.add(connection);
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
}
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=utf8 username=root password=root
测试类:
package com.rookie.bigdata.datasource;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import static org.junit.Assert.*;
/**
* @author
* @date 2019/1/13
*/
public class MyDataSourceTest {
@Test
public void test1() throws SQLException {
MyDataSource myDataSource = new MyDataSource();
Connection connection = myDataSource.getConnection();
String sql = "insert into H_USER values(?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
preparedStatement.setString(2, "张三");
preparedStatement.setInt(3, 23);
int rows = preparedStatement.executeUpdate();
System.out.println(rows);
myDataSource.releaseConnetion(connection);
}
}
java自定义连接池改进
实现Connection接口
package com.rookie.bigdata.datasource;
import java.sql.*;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
/**
* @author
* @date 2019/1/13
*/
//实现一个Connection接口
public class MyConnection implements Connection {
//定义一个变量
private Connection connection;
private LinkedList<Connection> pool;
//编写构造方法
public MyConnection(Connection connection, LinkedList<Connection> pool){
this.connection=connection;
this.pool=pool;
}
@Override
public void close() throws SQLException {
pool.add(connection);
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return connection.prepareStatement(sql);
}
@Override
public Statement createStatement() throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return null;
}
@Override
public String nativeSQL(String sql) throws SQLException {
return null;
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
}
@Override
public boolean getAutoCommit() throws SQLException {
return false;
}
@Override
public void commit() throws SQLException {
}
@Override
public void rollback() throws SQLException {
}
@Override
public boolean isClosed() throws SQLException {
return false;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return null;
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
}
@Override
public boolean isReadOnly() throws SQLException {
return false;
}
@Override
public void setCatalog(String catalog) throws SQLException {
}
@Override
public String getCatalog() throws SQLException {
return null;
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
}
@Override
public int getTransactionIsolation() throws SQLException {
return 0;
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return null;
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return null;
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
}
@Override
public void setHoldability(int holdability) throws SQLException {
}
@Override
public int getHoldability() throws SQLException {
return 0;
}
@Override
public Savepoint setSavepoint() throws SQLException {
return null;
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return null;
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return null;
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return null;
}
@Override
public Clob createClob() throws SQLException {
return null;
}
@Override
public Blob createBlob() throws SQLException {
return null;
}
@Override
public NClob createNClob() throws SQLException {
return null;
}
@Override
public SQLXML createSQLXML() throws SQLException {
return null;
}
@Override
public boolean isValid(int timeout) throws SQLException {
return false;
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
}
@Override
public String getClientInfo(String name) throws SQLException {
return null;
}
@Override
public Properties getClientInfo() throws SQLException {
return null;
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return null;
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return null;
}
@Override
public void setSchema(String schema) throws SQLException {
}
@Override
public String getSchema() throws SQLException {
return null;
}
@Override
public void abort(Executor executor) throws SQLException {
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
}
@Override
public int getNetworkTimeout() throws SQLException {
return 0;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}
package com.rookie.bigdata.datasource;
import com.rookie.bigdata.utils.JDBCUtils;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;
/**
* @author liuxili
* @date 2019/1/13
*/
public class MyDataSource1 implements DataSource {
//创建一个容器,用于存放connection对象
private static LinkedList<Connection> pool = new LinkedList<>();
//初始化5个连接,放到容器中
static {
for (int i = 0; i < 5; i++) {
Connection connection = JDBCUtils.getConnection();
MyConnection myConnection= new MyConnection(connection,pool);
pool.add(myConnection);
}
}
/**
* 获取连接的方法
*
* @return
* @throws SQLException
*/
@Override
public Connection getConnection() throws SQLException {
Connection connection=null;
//当连接池中没有连接的时候,需要创建链接
if (pool.size() == 0) {
for (int i = 0; i < 5; i++) {
connection = JDBCUtils.getConnection();
MyConnection myConnection= new MyConnection(connection,pool);
pool.add(myConnection);
}
}
//从池中获取连接
return pool.remove(0);
}
// /**
// * 归还连接到连接池中
// *
// * @param connection
// */
// public void releaseConnetion(Connection connection) {
// pool.add(connection);
//
// }
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
}
测试代码
@Test
public void test2() throws SQLException {
MyDataSource1 myDataSource = new MyDataSource1();
Connection connection = myDataSource.getConnection();
String sql = "insert into H_USER values(?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,2);
preparedStatement.setString(2, "张三");
preparedStatement.setInt(3, 23);
int rows = preparedStatement.executeUpdate();
System.out.println(rows);
JDBCUtils.release(connection,preparedStatement,null);
}
至此自定义连接池实现完毕,参考黑马程序员视频教程
java自定义连接池的更多相关文章
- JAVA自定义连接池原理设计(一)
一,概述 本人认为在开发过程中,需要挑战更高的阶段和更优的代码,虽然在真正开发工作中,代码质量和按时交付项目功能相比总是无足轻重.但是个人认为开发是一条任重而道远的路.现在本人在网上找到一个自定义连接 ...
- JDBC连接池-自定义连接池
JDBC连接池 java JDBC连接中用到Connection 在每次对数据进行增删查改 都要 开启 .关闭 ,在实例开发项目中 ,浪费了很大的资源 ,以下是之前连接JDBC的案例 pack ...
- JDBC连接池原理、自定义连接池代码实现
首先自己实现一个简单的连接池: 数据准备: CREATE DATABASE mybase; USE mybase; CREATE TABLE users( uid INT PRIMARY KEY AU ...
- JDBC自定义连接池
开发中,"获得连接"和"释放资源"是非常消耗系统资源的,为了解决此类性能问题可以采用连接池技术来共享连接Connection. 1.概述 用池来管理Connec ...
- MySQL学习(六)——自定义连接池
1.连接池概念 用池来管理Connection,这样可以重复使用Connection.有了池,我们就不用自己来创建Connection,而是通过池来获取Connection对象.当使用完Connect ...
- SpringBoot 整合mongoDB并自定义连接池
SpringBoot 整合mongoDB并自定义连接池 得力于SpringBoot的特性,整合mongoDB是很容易的,我们整合mongoDB的目的就是想用它给我们提供的mongoTemplate,它 ...
- 自定义连接池DataSourse
自定义连接池DataSourse 连接池概述: 管理数据库的连接, 作用: 提高项目的性能.就是在连接池初始化的时候存入一定数量的连接,用的时候通过方法获取,不用的时候归还连接即可.所有的连接池必须实 ...
- Java Mysql连接池配置和案例分析--超时异常和处理
前言: 最近在开发服务的时候, 发现服务只要一段时间不用, 下次首次访问总是失败. 该问题影响虽不大, 但终究影响用户体验. 观察日志后发现, mysql连接因长时间空闲而被关闭, 使用时没有死链检测 ...
- Java 自定义线程池
Java 自定义线程池 https://www.cnblogs.com/yaoxiaowen/p/6576898.html public ThreadPoolExecutor(int corePool ...
随机推荐
- JavaScript引用类型之Array类型API详解
Array类型也是ECMASCRIPT中最常见的数据类型,而且数据的每一项可以保存任何类型的数值,而且数组的大小是可以动态调整的,可以随着数据的添加自动增长以容纳新的数据.下面,总结数据的一些常用方法 ...
- 深度辨析 Python 的 eval() 与 exec()
Python 提供了很多内置的工具函数(Built-in Functions),在最新的 Python 3 官方文档中,它列出了 69 个. 大部分函数是我们经常使用的,例如 print().open ...
- Java进阶篇设计模式之十一 ---- 策略模式和模板方法模式
前言 在上一篇中我们学习了行为型模式的访问者模式(Visitor Pattern)和中介者模式(Mediator Pattern).本篇则来学习下行为型模式的两个模式,策略模式(Strategy Pa ...
- 8天入门docker系列 —— 第五天 使用aspnetcore小案例熟悉容器互联和docker-compose一键部署
这一篇继续完善webnotebook,如果你读过上一篇的内容,你应该知道怎么去挂载webnotebook日志和容器的远程访问,但是这些还远不够,webnotebook 总要和一些数据库打交道吧,比如说 ...
- 调用pymysql模块操作数据库
1.创建数据库表: def create_table(tb_name): import pymysql#导入模块 #连接数据库 db = pymysql.Connect(','zabbix_db') ...
- 浅谈java线程池实现
再进入主题之前,我们先了解几个概念,对读源码有所帮助,对于线程池的运行状态,有4个级别,分别是RUNNING,SHUTING,STOP,TIDING,TERMINATED 解释如下: The runS ...
- GIS中的坐标系【Esri官方文档部分翻译】
GCS 地理坐标系(GCS)使用椭圆体表面来定义地球上的位置.地理坐标系有三个部分: 基准面,是地球的椭圆体(椭球体)模型 本初子午线 角度单位 常见基准包括WGS84(用于GPS)和NAD83(用于 ...
- android:layout_weight属性详解
weight:重量.权重. 当我们给一个view设置了android:layout_weight属性,意味着赋予它话语权,常规思维就是谁的weight大,谁说了算(空间占比大). 下面我们来看下具体的 ...
- vivo4.0系统怎么不ROOT激活Xposed框架的教程
在越来越多应用室的引流,或业务操作中,大多数需要使用安卓的强大Xposed框架,前几天,我们应用室采购了一批新的vivo4.0系统,大多数都是基于7.0以上系统,大多数不能够刷入Root的su权限,即 ...
- String、StringBuffer和StringBuilder类的区别
Java提供了String.StringBuffer和StringBuilder类来封装字符串,并提供了一系列操作字符串对象的方法. 它们的相同点是都用来封装字符串:都实现了CharSequence接 ...