1.流程
创建linkedlist集合用来充当容器存储连接
读取properties配置文件,
注册驱动
初始化连接
连接数据库
将链接放入集合中
package com.gxa;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.Properties;
import java.util.logging.Logger;
public class DataPoolSource implements DataSource {
//创建一个LinkedList集合,用来装创建的链接
private LinkedList<Connection> conns = new LinkedList<>();
private static Properties properties = new Properties();
//链接数据库:注册驱动,读取db.properties中的数据,链接数据库,将该段代码写在静态块中
static {
try {
//读内容
InputStream in = DataPoolSource.class.getClassLoader().getResourceAsStream("db.properties");
properties.load(in);
//注册驱动
Class.forName(properties.getProperty("driver"));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
//初始化链接
public DataPoolSource() {
for (int i = 0; i < 10; i++) {
try {
Connection conn = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
//通过动态代理(Proxy)完成连接的创建和归还
conns.add((Connection) Proxy.newProxyInstance(DataPoolSource.class.getClassLoader(),
new Class[]{Connection.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (!method.getName().equals("close")) {
return method.invoke(conn, args);
}
conns.add(conn);
System.out.println("再次添加一个链接" + conns.size());
return null;
}
}
)
);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//将链接放入集合中
@Override
public Connection getConnection() throws SQLException {
//从集合中取出连接
Connection connection = conns.removeFirst();
return 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;
}
}
测试代码
package com.gxa;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
public class TestDataSource {
@Test
public void test1() throws SQLException {
DataPoolSource dataPoolSource = new DataPoolSource();
Connection connection = dataPoolSource.getConnection();
System.out.println(connection);
connection.close();
}
}
|