1. 原理代码示例

public class JdbcPool implements DataSource {

	private static LinkedList<Connection> list = new LinkedList<Connection>();

	static{
try{
InputStream in = JdbcPool.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(in); String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password"); Class.forName(driver); for(int i=0;i<10;i++){
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("获取到了链接" + conn);
list.add(conn);
} }catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
} /*
1.写一个子类,覆盖close方法
2、写一个connection的包装类,增强close方法
3、用动态代理,返回一个代理对象出去,拦截close方法的调用,对close进行增强
*/ public Connection getConnection() throws SQLException { //proxyConnection.commit() proxyConnection.rollback
if(list.size()>0){
final Connection conn = list.removeFirst(); //myconnection.commit
System.out.println("池大小是" + list.size());
return (Connection) Proxy.newProxyInstance(JdbcPool.class.getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler(){ public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(!method.getName().equals("close")){
return method.invoke(conn, args);
}else{
list.add(conn);
System.out.println(conn + "被还给池了!!");
System.out.println("池大小为" + list.size());
return null;
} } }); }else{
throw new RuntimeException("对不起,数据库忙");
} } public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
return null;
} public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
} public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
} public void setLogWriter(PrintWriter arg0) throws SQLException {
// TODO Auto-generated method stub } public void setLoginTimeout(int arg0) throws SQLException {
// TODO Auto-generated method stub }
} /*
用包装设计模式对某个对象进行增强
1.写一个类,实现与被增强对象(mysql的connection)相同的接口
2、定义一个变量,指向被增强对象
3、定义一个构造方法,接收被增强对象
4、覆盖想增强的方法
5、对于不想增强的方法,直接调用被增强对象的方法
*/ class MyConnection implements Connection{ private Connection conn;
private List pool;
public MyConnection(Connection conn,List pool){
this.conn = conn;
this.pool = pool;
} public void close() throws SQLException {
pool.add(conn);
} public void clearWarnings() throws SQLException {
this.conn.clearWarnings(); } public void commit() throws SQLException {
this.conn.commit(); }
public Statement createStatement() throws SQLException {
return this.conn.createStatement();
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return false;
}
public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return false;
}
public String nativeSQL(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public CallableStatement prepareCall(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub }
public void rollback() throws SQLException {
// TODO Auto-generated method stub }
public void rollback(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub }
public void setAutoCommit(boolean autoCommit) throws SQLException {
// TODO Auto-generated method stub }
public void setCatalog(String catalog) throws SQLException {
// TODO Auto-generated method stub }
public void setHoldability(int holdability) throws SQLException {
// TODO Auto-generated method stub }
public void setReadOnly(boolean readOnly) throws SQLException {
// TODO Auto-generated method stub }
public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public Savepoint setSavepoint(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void setTransactionIsolation(int level) throws SQLException {
// TODO Auto-generated method stub }
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
// TODO Auto-generated method stub } }

2. 开源连接池  •DBCP
数据库连接池

加入dbcp链接池

1.导入jar包

 commons-dbcp-1.2.2.jar  commons-pool.jar

2、在类目录下加入dbcp的配置文件:dbcpconfig.properties

3、在jdbcUtils的静态代码块中创建池

private static DataSource ds = null;
static{
try{
InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties prop = new Properties();
prop.load(in); BasicDataSourceFactory factory = new BasicDataSourceFactory(); ds = factory.createDataSource(prop);
System.out.println(ds);
}catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}

重写后的工具类

public class JdbcUtils_DBCP {

	private static DataSource ds = null;
static{
try{
InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties prop = new Properties();
prop.load(in); BasicDataSourceFactory factory = new BasicDataSourceFactory(); ds = factory.createDataSource(prop);
System.out.println(ds);
}catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
} public static Connection getConnection() throws SQLException{ return ds.getConnection();
} public static void release(Connection conn,Statement st,ResultSet rs){ if(rs!=null){
try{
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
rs = null; }
if(st!=null){
try{
st.close();
}catch (Exception e) {
e.printStackTrace();
} } if(conn!=null){
try{
conn.close();
}catch (Exception e) {
e.printStackTrace();
} }
} }

配置文档dbcpconfig.properties

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc
username=root
password=root #<!-- 初始化连接 -->
initialSize=10 #最大连接数量
maxActive=50 #<!-- 最大空闲连接 -->
maxIdle=20 #<!-- 最小空闲连接 -->
minIdle=5 #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000 #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8 #指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true #driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly= #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=REPEATABLE_READ

3.开源数据库连接池  •C3P0
数据库连接池

配置文档 c3p0-config.xml 需要放在 src目录下,自动搜索

<?xml version="1.0" encoding="UTF-8"?>

<!--
c3p0-config.xml
private static ComboPooledDataSource ds;
static{
try {
ds = new ComboPooledDataSource("c3p0config");
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
} --> <c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/transaction</property>
<property name="user">root</property>
<property name="password">123456</property> <property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">100</property> </default-config> <named-config name="c3p0config">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/transaction</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">100</property><!-- intergalactoApp adopts a different approach to configuring statement caching -->
</named-config> </c3p0-config>

工具类:

public class JdbcUtils_C3P0 {

	private static ComboPooledDataSource ds = null;
static{
try{
ds = new ComboPooledDataSource("c3p0config"); }catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
} public static Connection getConnection() throws SQLException{ return ds.getConnection();
} public static void release(Connection conn,Statement st,ResultSet rs){ if(rs!=null){
try{
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
rs = null; }
if(st!=null){
try{
st.close();
}catch (Exception e) {
e.printStackTrace();
} } if(conn!=null){
try{
conn.close();
}catch (Exception e) {
e.printStackTrace();
} }
} }

Java -- JDBC 数据库连接池的更多相关文章

  1. Java jdbc数据库连接池总结!(转)

    1. 引言 近年来,随着Internet/Intranet建网技术的飞速发展和在世界范围内的迅速普及,计算机 应用程序已从传统的桌面应用转到Web应用.基于B/S(Browser/Server)架构的 ...

  2. JAVA jdbc(数据库连接池)学习笔记(二) SQL注入

    PS:今天偶然间发现了SQL的注入...所以就简单的脑补了一下,都是一些简单的例子...这篇写的不怎么样...由于自己没有进行很深的研究... 学习内容: 1.SQL注入的概念...   所谓SQL注 ...

  3. JAVA jdbc(数据库连接池)学习笔记(一)

    学习内容: 1.JDBC的含义... JDBC想必学过JAVA的就不会陌生,JDBC到底是什么呢?其实就是由JAVA的一些类和接口构成的API,保存在java.sql和javax.sql..包中的一些 ...

  4. JAVA jdbc(数据库连接池)学习笔记(转)

    学习内容: 1.JDBC的含义... JDBC想必学过JAVA的就不会陌生,JDBC到底是什么呢?其实就是由JAVA的一些类和接口构成的API,保存在java.sql和javax.sql..包中的一些 ...

  5. Java自学-JDBC 数据库连接池

    数据库连接池 与线程池类似的,数据库也有一个数据库连接池. 不过他们的实现思路是不一样的. 本章节讲解了自定义数据库连接池类:ConnectionPool,虽然不是很完善和健壮,但是足以帮助大家理解C ...

  6. JAVA之JDBC数据库连接池总结篇

    JDBC数据库连接池 一.JDBC数据库连接池的必要性 二.数据库连接池技术 三.多种开源的数据库连接池 3.1 C3P0数据库连接池 3.2 DBCP数据库连接池 3.3 Druid(德鲁伊)数据库 ...

  7. JAVA基础知识之JDBC——JDBC数据库连接池

    JDBC数据库连接池 数据库的连接和关闭是很耗费资源的操作,前面介绍的DriverManager方式获取的数据库连接,一个Connection对象就对应了一个物理数据库连接,每次操作都要打开一个连接, ...

  8. JDBC数据库连接池技术

    在JDBC中,获得连接或释放资源是非常消耗系统资源的两个过程,为了解决此类性能问题,通常采用连接池技术,来共享连接.这样我们就不需要每次都创建连接.释放连接了,这些操作都交给了连接池. 用池的概念来管 ...

  9. java配置数据库连接池的方法步骤

    java配置数据库连接池的方法步骤 java配置数据库连接池的方法步骤,需要的朋友可以参考一下   先来了解下什么是数据库连接池数据库连接池技术的思想非常简单,将数据库连接作为对象存储在一个Vecto ...

随机推荐

  1. poj2420(模拟退火大法好)

    // // main.cpp // poj2420 // // Created by 陈加寿 on 16/2/13. // Copyright © 2016年 chenhuan001. All rig ...

  2. Velocity模版引擎使用总结

    Velocity是一个基于java的模板引擎.它允许任何人仅仅简单的使用模板语言来引用由java代码定义的对象. 当Velocity应用于web开发时,界面设计人员可以和java程序开发人员同步开发一 ...

  3. the core of Git is a simple key-value data store The objects directory stores all the content for your database

    w https://git-scm.com/book/en/v1/Git-Internals-Plumbing-and-Porcelain Git is a content-addressable f ...

  4. Time-series Storage Layer Time Series Databases 时间序列

    w 关于时间序列数据库的思考-CSDN.NET  http://www.csdn.net/article/2015-07-13/2825192  存储和处理时间序列数据(“Time Series Da ...

  5. 通过天天模拟器加burpsuite抓取手机app流量

    通过天天模拟器,代理抓取安卓app数据包.也可以抓取https. 1.下载天天模拟器,官方下载即可,下载安装. 2.启动天天模拟器,设置代理,点击上方wlan设置图标,打开wlan设置,如下: 3.鼠 ...

  6. Hash表的C++实现(转)

    原文:Hash表(C++实现) 哈希表的几个概念: 映像:由哈希函数得到的哈希表是一个映像. 冲突:如果两个关键字的哈希函数值相等,这种现象称为冲突. 处理冲突的几个方法: 1.开放地址法:用开放地址 ...

  7. PAT 1072. 开学寄语(20) JAVA

    下图是上海某校的新学期开学寄语:天将降大任于斯人也,必先删其微博,卸其QQ,封其电脑,夺其手机,收其ipad,断其wifi,使其百无聊赖,然后,净面.理发.整衣,然后思过.读书.锻炼.明智.开悟.精进 ...

  8. C语言中的const,free使用方法具体解释

    注意:C语言中的const和C++中的const是有区别的,并且在使用VS编译測试的时候. 假设是C的话.请一定要建立一个后缀为C的文件.不要是CPP的文件. 由于.两个编译器会有区别的. 一.C语言 ...

  9. Python通过fork的方式防止僵尸进程

    import subprocess import os import sys import platform def fock_new(func): def inner(*args, **kwargs ...

  10. ABAP锁,数据库锁

    原文出自 江正军 技术博客,博客链接:www.cnblogs.com/jiangzhengjun ABAP数据锁定 SM12锁查看与维护 通用加锁与解锁函数 ABAP程序锁定 数据库锁 锁的分类和兼容 ...