数据源,动态代理

来源:互联网 发布:ubuntu和ubuntu mate 编辑:程序博客网 时间:2024/05/29 19:05
package com.huowolf.jdbc.pool;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;import javax.sql.DataSource;//一个标准的数据源public class MyDataSource1 implements DataSource {private static String driverClassName;private static String url;private static String user;private static String password;private static LinkedList<Connection> pool = new LinkedList<Connection>();//存储连接的池static{try {InputStream in = com.huowolf.JdbcUtil.JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");Properties props = new Properties();props.load(in);driverClassName = props.getProperty("driverClassName");url = props.getProperty("url");user = props.getProperty("user");password = props.getProperty("password");Class.forName(driverClassName);//初始化10个连接到池中for(int i=0;i<10;i++){Connection conn = DriverManager.getConnection(url, user, password);pool.add(conn);}} catch (Exception e) {e.printStackTrace();}}//从池中获取一个连接@Overridepublic synchronized Connection getConnection() throws SQLException {if(pool.size()>0){final Connection conn = pool.remove();//原有对象//返回动态代理对象return (Connection)Proxy.newProxyInstance(conn.getClass().getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {if("close".equals(method.getName())){return pool.add(conn);}else{return method.invoke(conn, args);}}});}else{throw new RuntimeException("对比起!服务器真忙");}}@Overridepublic Connection getConnection(String username, String password)throws SQLException {return null;}@Overridepublic PrintWriter getLogWriter() throws SQLException {return null;}@Overridepublic int getLoginTimeout() throws SQLException {return 0;}@Overridepublic void setLogWriter(PrintWriter out) throws SQLException {}@Overridepublic void setLoginTimeout(int seconds) throws SQLException {}@Overridepublic boolean isWrapperFor(Class<?> iface) throws SQLException {return false;}@Overridepublic <T> T unwrap(Class<T> iface) throws SQLException {return null;}@Overridepublic Logger getParentLogger() throws SQLFeatureNotSupportedException {return null;}}

0 0
原创粉丝点击