首先创建一个配置文件driver.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydemo
username=root
password=password
init=10
maxsize=20
maxwait=500
validationQuery=select 1
public class NormalLinkedPool {
public static Connection getConnection() {
return Pool.getConnection();
}
public static void destory(Connection connection) {
Pool.destoryConnection(connection);
}
private static class Pool {
private static String DRIVER;
private static String URL;
private static String USERNAME;
private static String PASSWORD;
private static int INIT;
private static int MAXSIZE;
private static Long MAXWAIT;
private static String VALIDATIONQUERY;
//创建连接创建对象
private static List<ConnectionEntity> pools = new ArrayList<>();
static {
//读取属性文件获得配置
loadProperties();
for (int i = 0; i <= INIT; i++) {
pools.add(buildConnection());
}
}
private static void loadProperties() {
try {
String path = URLDecoder.decode(NormalLinkedPool.class.getResource("/driver.properties").getPath(), "utf-8");
Properties pop = new Properties();
pop.load(new FileInputStream(path));
DRIVER = pop.getProperty("driver");
URL = pop.getProperty("url");
USERNAME = pop.getProperty("username");
PASSWORD = pop.getProperty("password");
INIT = Integer.parseInt(pop.getProperty("init"));
MAXSIZE = Integer.parseInt(pop.getProperty("maxsize"));
MAXWAIT = Long.parseLong(pop.getProperty("maxwait"));
VALIDATIONQUERY = pop.getProperty("validationQuery");
} catch (IOException e) {
e.printStackTrace();
}
}
//创建连接
private static ConnectionEntity buildConnection() {
//System.out.println("连接池当前连接数:=============================>"+pools.size());
Connection con = null;
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return ConnectionEntity.builder().conn(con).build();
}
//用户获取连接方法
public static Connection getConnection() {
//在pools里面先查询是否有空闲的连接,如果有就直接发送给用户
for (ConnectionEntity connectionEntity : pools) {
if (!connectionEntity.isBusy()) {
connectionEntity.setBusy(true);
return connectionEntity.getConn();
}
}
//如果在上一步中发现没有空闲连接,就用当前的连接个数和最大连接个数比较如果当前连接小于
//最大连接数,就新创建一个连接发送给用户,并把链接设置为忙并存放在pool中
if (pools.size() < MAXSIZE) {
ConnectionEntity conn = buildConnection();
conn.setBusy(true);
pools.add(conn);
return conn.getConn();
}
//如果没有空线连接,并且连接数已达上限,则用户等待
try {
Thread.sleep(MAXWAIT);
} catch (InterruptedException e) {
e.printStackTrace();
}
return getConnection();
}
//用户释放连接方法
public static void destoryConnection(Connection connection) {
//找到用户连接是否良好
try {
PreparedStatement pstat = connection.prepareStatement(VALIDATIONQUERY);
pstat.executeQuery();
//如果没有出现异常就继续下一步工作 将用户归还的连接设置空闲
for (ConnectionEntity connectionEntity : pools) {
if (connectionEntity.getConn() == connection) {
connectionEntity.setBusy(false);
}
}
} catch (SQLException e) {
//出现异常移除连接
for (ConnectionEntity connectionEntity : pools) {
if (connectionEntity.getConn() == connection) {
pools.remove(connectionEntity);
break;
}
}
}
}
}