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 ...
随机推荐
- .Net Core中利用TPL(任务并行库)构建Pipeline处理Dataflow
在学习的过程中,看一些一线的技术文档很吃力,而且考虑到国内那些技术牛人英语都不差的,要向他们看齐,所以每天下班都在疯狂地背单词,博客有些日子没有更新了,见谅见谅 什么是TPL? Task Parall ...
- 使用kibana可视化报表实时监控你的应用程序,从日志中找出问题,解决问题
先结果导向,来看我在kibana dashborad中制作的几张监控图. 一:先睹为快 dashboard1:监控几个维度的日志,这么点日志量是因为把无用的清理掉了,而且只接入了部分应用. <1 ...
- 分享自己写的一个.net方法缓存源码
在服务器性能优化中,我们更多的是要考虑到缓存的使用,分享一个自己编写的方法缓存的框架,使用非常方便.话不多说,先上使用例子: 1.定义要使用缓存的类及方法: public class Example ...
- SpringIOC原理简述
IOC:控制反转(Inversion of Control,英文缩写为 IOC) 简单来讲就是把代码的控制权从调用方(用户)转变成被调用方(服务端) 以前的代码控制权在调用方,所以要每当程序要更新修改 ...
- Windows Server 2016-Powershell加域并指定OU (二)
上章节提到通过netdom join加域并指定对应OU,本章再补充一例现成powershell加域并指定对应OU的脚本,便于大家工作中使用. $PlainPassword = P@ssw0rd $Us ...
- 我为什么推荐你使用kindle
我为什么推荐你使用kindle kindle 分 kindle 电子阅读器,pc 版,app 版,下文主要介绍 Amazon 设计和销售的电子书阅读器. 亚马逊官方出的 kindle 使用技巧 使用 ...
- redis缓存类
<?php class Redis_model{ public $redis = null; public function __construct() { $hosts = $this-> ...
- .NET Core 时代已经到了,你准备好了吗
今天很多人都收到了阿里云函数计算支持.NET Core的短信了. 通过访问 https://help.aliyun.com/document_detail/112379.html 你可以看到最新的说明 ...
- 从 RegExp 构造器看 JS 字符串转义设计
多年前我第一次入职腾讯的时候,DC 从杭州给我寄来了一本他刚翻译出炉的<高性能 JavaScript>.那段时间为了帮忙校对,我仔细阅读了书中的每一个段落,结果积累了不少 JavaScri ...
- Java核心技术第五章——1.类、超类、子类(1)
1.定义子类: 关键字extends表明正在构造的新类派生与一个已存在的类.已存在的类称为超类.基类或父类:新类称为子类.派生类或孩子类.超类和子类是Java程序员最常用的两个术语(emmm~~我觉得 ...