parent
fced6a0cdc
commit
fca0a27781
@ -0,0 +1,77 @@
|
||||
package com.msb.dao;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class MyConnectionPool {
|
||||
|
||||
private static String driver = "com.mysql.cj.jdbc.Driver";
|
||||
private static String url = "jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
|
||||
private static String user = "root";
|
||||
private static String password = "Fnst1234";
|
||||
|
||||
private static int initSize = 5;
|
||||
|
||||
private static int maxSize = 10;
|
||||
|
||||
private static LinkedList<Connection> pool = new LinkedList<Connection>();
|
||||
|
||||
static {
|
||||
try {
|
||||
Class.forName(driver);
|
||||
|
||||
for (int i = 0; i < initSize; i++) {
|
||||
Connection connection = initConnection();
|
||||
if (connection != null) {
|
||||
pool.add(connection);
|
||||
}
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection initConnection() {
|
||||
try {
|
||||
return DriverManager.getConnection(url, user, password);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Connection getConnection() {
|
||||
Connection connection =null;
|
||||
if (pool.size() > 0) {
|
||||
connection = pool.removeFirst();
|
||||
}
|
||||
else {
|
||||
connection = initConnection();
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
|
||||
public static void returnConnection(Connection connection) {
|
||||
if (connection == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (connection.isClosed()) {
|
||||
return;
|
||||
}
|
||||
if (pool.size() < maxSize) {
|
||||
connection.setAutoCommit(true);
|
||||
pool.addLast(connection);
|
||||
}
|
||||
else {
|
||||
connection.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in new issue