JDBC数据库连接池JAVA

//JDBC JAVA 代码编写,代码属于初级阶段,后续有待更新。

public class ConnBean {
//db连接参数
private String driver;
private String url;
private String username;
private String password;
private String cname;//连接名字
private int initcount = 5;//初始化连接数
private int freemaxcount = 20;//初始化连接数
private int maxcount = 100;//最大连接数
private boolean status = false;//状态
private boolean isCheck = false;//是否查看日志,默认false
private boolean isdestory = false;//是否定时销毁,默认fasle
private long delay = 1000*5;//多久开始检查
private long period = 1000*10;//检查频率

public ConnBean() {
super();
}

public ConnBean(String driver, String url, String username, String password) {
super();
this.driver = driver;
this.url = url;
this.username = username;
this.password = password;
}

public String getDriver() {
return driver;
}

public void setDriver(String driver) {
this.driver = driver;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getCname() {
return cname;
}

public void setCname(String cname) {
this.cname = cname;
}

public int getInitcount() {
return initcount;
}

public void setInitcount(int initcount) {
this.initcount = initcount;
}

public int getMaxcount() {
return maxcount;
}

public void setMaxcount(int maxcount) {
this.maxcount = maxcount;
}

public boolean isStatus() {
return status;
}

public void setStatus(boolean status) {
this.status = status;
}

public boolean isCheck() {
return isCheck;
}

public void setCheck(boolean isCheck) {
this.isCheck = isCheck;
}

public long getDelay() {
return delay;
}

public void setDelay(long delay) {
this.delay = delay;
}

public long getPeriod() {
return period;
}

public void setPeriod(long period) {
this.period = period;
}

public boolean isIsdestory() {
return isdestory;
}

public void setIsdestory(boolean isdestory) {
this.isdestory = isdestory;
}

public int getFreemaxcount() {
return freemaxcount;
}

public void setFreemaxcount(int freemaxcount) {
this.freemaxcount = freemaxcount;
}
}

 

//数据库连接池

 

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

public class ConnectionPool implements IConnPool{

ConnBean connBean = null;//配置实体
public int connCount = 0;//连接数
public boolean isDestory = false;//销毁判断
LinkedList<Connection> freeList = new LinkedList<Connection>();//方便移动删除连接池的连接
LinkedList<Connection> activeList = new LinkedList<Connection>();
static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();//线程事务统一

public ConnectionPool(ConnBean connBean) {
this.connBean = connBean;
init();
}

/**
* 初始化
*/

private void init() {

Connection conn = null;
for(int i=0;i<connBean.getInitcount();i++) {
conn = createConnection();
freeList.add(conn);
}
// System.out.println("freelist=============="+freeList.size());
checkPool();
//定时销毁
if(connBean.isIsdestory()) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
destory();
}
}, 10000,1000*60*10);//十分钟一次清空数据库连接池,(初级方案)
}
}
public synchronized Connection getConnection() {
if(isDestory) {
try {
wait(3000);//等待3秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Connection conn = null;
conn=getThreaConn();//获取当前线程连接
if(conn!=null) {
Log("thredlocal获取成功->:"+conn);
connCount++;
return conn;
}
Log("thredlocal获取失败->从空闲连接池获取");
try {
if(freeList.size()>0) {
conn =freeList.removeFirst();
threadLocal.set(conn);
Log("空闲连接池获取成功!");
connCount++;
}else {
if(activeList.size()<connBean.getMaxcount())//如果小于最大连接数
{
conn=createConnection();
activeList.add(conn);
threadLocal.set(conn);
connCount++;
Log("空闲连接池用完了,建立新连接,并放入活动连接池队列");
}else {
wait();//等待其他连接释放
Log("有一个连接被释放,抢抢抢!");
getConnection();//递归调用自己
}
}
} catch (InterruptedException e) {
Log("wait()方法报错");
e.printStackTrace();
}
Log("当前Connect对象是:"+conn);

try {
ResultSet rs =conn.createStatement().executeQuery("select logname from tbluser where logname=‘admin‘");
if(rs.next()){
rs.close();
return conn;
}else{
freeList.remove(conn);
threadLocal.remove();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}
public synchronized Connection createConnection() {
Connection conn = null;
try {
Class.forName(connBean.getDriver());
conn=DriverManager.getConnection(connBean.getUrl(), connBean.getUsername(), connBean.getPassword());
} catch (ClassNotFoundException e) {
Log("jdbc驱动加载失败!");
e.printStackTrace();
} catch (SQLException e) {
Log("数据库连接字失败!");
e.printStackTrace();
}
return conn;
}
public Connection getThreaConn() {
Connection conn = threadLocal.get();//获取当前连接池,超时会失败,获取新的一个连接
if(checkConn(conn)) {
return conn;
}
return null;
}

public synchronized void release(Connection conn) {

if(checkConn(conn)) {

if(freeList.size()<connBean.getFreemaxcount()) {//如果最大空闲连接池数
freeList.add(conn);
Log("成功添加空闲池");
}
Log("是否从活动连接池移除成功"+activeList.remove(conn));
connCount--;
threadLocal.remove();
Log("成功释放连接");
notifyAll();//通知正在等待的线程
}

}

public void destory() {
try {
isDestory=true;//正在执行销毁
// 空闲连接池暂时没有销毁。
// Iterator<Connection> itfree = freeList.iterator();
// while (itfree.hasNext()) {
// Connection conn = itfree.next();
// conn.close();
// itfree.remove();
// }
Iterator<Connection> itactive = activeList.iterator();//迭代器方式删除
while (itactive.hasNext()) {
Connection conn = itactive.next();
conn.close();
itactive.remove();
}
Log("销毁成功");
connCount=connBean.getFreemaxcount()-freeList.size();//正在连接的数量
} catch (SQLException e) {
e.printStackTrace();
}finally {
isDestory=false;//销毁完成
}
}

public synchronized void checkPool() {
if(connBean.isCheck())
{
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Log("空闲连接池:"+freeList.size()+"个,活动连接池:"+activeList.size()+"个,连接次数:"+connCount);
LogConn("Logfree连接池队列:",freeList);
LogConn("Logactive连接池队列:",activeList);
System.out.println("\n");
}
}, connBean.getDelay(),connBean.getPeriod());

}

}

public boolean checkConn(Connection conn) {//检查conn是否可用

if(conn != null ) {
return true;
}

return false;
}
private void Log(String logStr) {
System.out.println(logStr);
}
private void LogConn(String name,LinkedList<Connection> list) {
System.out.print(name);
if(list.isEmpty()) {
return;
}
Iterator<Connection> it = list.iterator();
while (it.hasNext()) {
Connection conn = it.next();
System.out.print(conn.toString().replaceAll("com.microsoft.sqlserver.jdbc.SQLServerConnection@", "@"));
}

}
}

 

//通用接口

 

import java.sql.Connection;
/**
* 连接池接口(初级)
* @author sun
*
*/
public interface IConnPool {
/**
* 获取数据库连接对象
* @return Connection
*/
public Connection getConnection();
/**
* 创建新数据库对象
*/
public Connection createConnection();
/**
* 获取当前数据库连接对象
* @return Connection
*/
public Connection getThreaConn();
/**
* 释放数据库连接对象
* @param conn
*/
public void release(Connection conn);
/**
* 销毁所有数据库对象
*/
public void destory();
/**
* 定时检查日志,方便查看连接池状态
*/
public void checkPool();
/**
* 检查数据库连接对象是否可用
* @return
*/
public boolean checkConn(Connection conn);
}

 

//数据库管理对象

 

 

import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;

public class PoolManger {
private static PoolManger poolManger = null;
private ConnectionPool connectionPool = null;
private PoolManger() {
Properties prop = new Properties();
try {
prop.load(getClass().getResourceAsStream("jdbc.properties"));
String driver = prop.getProperty("jdbc.driver");
String url = prop.getProperty("jdbc.url");
String username = prop.getProperty("jdbc.username");
String password = prop.getProperty("jdbc.password");
ConnBean connBean = new ConnBean(driver, url, username, password);
connectionPool = new ConnectionPool(connBean);
} catch (IOException e) {
System.out.println("读取配置文件失败");
e.printStackTrace();
}
}
static {
poolManger= new PoolManger();
System.out.println("数据库连接池初始化完成:)");
}
public static PoolManger getPoolManager() {
// System.out.println("有了");
if(poolManger==null)
{
poolManger = new PoolManger();
}
return poolManger;
}
public ConnectionPool getConnectionPool() {
if(connectionPool!=null) {
return connectionPool;
}
return null;
}
public void destory() {
if(connectionPool!=null) {
connectionPool.destory();
}
}
public void close(Connection conn) {
if(connectionPool!=null) {
connectionPool.release(conn);
}
}

}

//jdbc.properties放在同级目录下

jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;databaseName=xxx
jdbc.username=sa
jdbc.password=***

JDBC数据库连接池JAVA

上一篇:学习:inets


下一篇:SQL语句