[javaEE] 数据库连接池和动态代理

时间:2022-12-28 12:36:01

实现javax.sql.DataSource接口

实现Connection getConnection()方法

定义一个静态的成员属性LinkedList类型作为连接池,在静态代码块中初始化5条数据库连接,添加到连接池中,在getConnection方法中,当获取连接的时候在连接池中remove掉一条连接就可以了

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement; public class JDBCTest {
public static void main(String[] args) throws Exception {
//使用反射的方式
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接,导包的时候,注意要导java.sql下的,面向接口编程
MyPool pool=new MyPool();
Connection conn=pool.getConnection();
//获取传输器对象
Statement statement=conn.createStatement();
//获取结果集对象
ResultSet resultSet=statement.executeQuery("select * from user");
//遍历
while(resultSet.next()){
String username=resultSet.getString("username");
System.out.println(username);
}
//关闭资源
resultSet.close();
statement.close();
pool.resetConn(conn); }
}

我的连接池

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger; import javax.sql.DataSource; /**
* 手写连接池
*
* @author taoshihan
*
*/
public class MyPool implements DataSource {
// 连接池
public static List<Connection> pool = new LinkedList<Connection>();
// 初始化
static {
try {
Class.forName("com.mysql.jdbc.Driver");
for (int i = 0; i < 5; i++) {
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/java", "root", "root");
pool.add(conn);
}
} catch (Exception e) {
}
} /**
* 获取连接
*/
@Override
public Connection getConnection() throws SQLException {
// 如果池中没有连接
if (pool.size() == 0) {
for (int i = 0; i < 5; i++) {
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/java", "root", "root");
pool.add(conn);
}
}
//先进先出
Connection conn=pool.remove(0);
System.out.println("获取一个连接,池里还剩余"+pool.size());
return conn;
}
/**
* 重置连接
*/
public void resetConn(Connection conn){
try {
if(conn!=null && !conn.isClosed()){
pool.add(conn);
System.out.println("还回一个连接,池里还剩余"+pool.size());
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Connection getConnection(String username, String password)
throws SQLException {
return null;
} @Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub } @Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub } @Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
} @Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
} @Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
} }

使用继承,装饰,动态代理改造一个类中的方法

继承的缺点:此时我们已经得到了Connection对象,因此无法通过继承改造这个对象

装饰的测试实现:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement; public class JDBCTest {
public static void main(String[] args) throws Exception { //测试装饰模式
Animal dog=new BigDog(new Dog());
dog.eat();
dog.sound(); }
} /**
* 装饰模式测试
* @author taoshihan
*
*/
interface Animal{
public void eat();
public void sound();
}
class Dog implements Animal{ @Override
public void eat() {
System.out.println("吃");
} @Override
public void sound() {
System.out.println("汪");
}
}
//此时我想修改Dog类中的sound方法
class BigDog implements Animal{
private Dog dog;
public BigDog(Dog dog) {
this.dog=dog;
}
/**
* 这个方法调原来的
*/
@Override
public void eat() {
dog.eat();
}
/**
* 这个方法进行装饰
*/ @Override
public void sound() {
System.out.println("大叫");
} }

动态代理:

        //测试代理模式
final Dog dog=new Dog();
Animal proxy=(Animal) Proxy.newProxyInstance(Dog.class.getClassLoader(),Dog.class.getInterfaces() , new InvocationHandler() { @Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if("sound".equals(method.getName())){
System.out.println("大叫");
return null;
}else{
return method.invoke(dog, args);
}
}
});
proxy.eat();
proxy.sound();