免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1321 | 回复: 0
打印 上一主题 下一主题

最简单的数据库连接池 [复制链接]

论坛徽章:
1
程序设计版块每日发帖之星
日期:2015-07-10 22:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-09 11:05 |只看该作者 |倒序浏览
[代码][Java]代码
  1. package com.jxva.dao;

  2. import java.io.PrintWriter;
  3. import java.lang.reflect.InvocationHandler;
  4. import java.lang.reflect.Method;
  5. import java.lang.reflect.Proxy;
  6. import java.sql.Connection;
  7. import java.sql.DriverManager;
  8. import java.sql.SQLException;
  9. import java.sql.SQLFeatureNotSupportedException;
  10. import java.util.Date;
  11. import java.util.concurrent.ConcurrentHashMap;
  12. import java.util.concurrent.ConcurrentMap;
  13. import java.util.concurrent.Semaphore;

  14. import javax.sql.DataSource;

  15. import com.jxva.log.Logger;
  16. import com.jxva.util.RandomUtil;

  17. public class SimpleDataSource implements DataSource{

  18.     private String driverClass;
  19.     private String url;
  20.     private String username;
  21.     private String password;
  22.     private int minSize;
  23.     private int maxSize;

  24.     private static final Logger log = Logger.getLogger(SimpleDataSource.class);
  25.     private static final ConcurrentMap<Connection, Date> pool = new ConcurrentHashMap<Connection, Date>();
  26.     private Semaphore semaphore;
  27.      
  28.     public SimpleDataSource() {
  29.         minSize = 1;
  30.         maxSize = 5;
  31.         log.debug("Database Connection Pool initializing...");
  32.     }

  33.      
  34.     public void close(Connection conn) throws SQLException {
  35.         try{
  36.             synchronized (pool) {               
  37.                 if (pool.size() < maxSize) {
  38.                     pool.put(conn,new Date());
  39.                     return;
  40.                 }
  41.             }
  42.             conn.close();
  43.         }finally{
  44.             semaphore.release();
  45.         }
  46.     }

  47.     public void destroy() throws SQLException {
  48.         for (Connection conn : pool.keySet()) {
  49.             conn.close();
  50.         }
  51.         pool.clear();
  52.     }

  53.     @Override
  54.     public Connection getConnection() throws SQLException {
  55.         try {
  56.             semaphore.acquire();
  57.         } catch (InterruptedException e1) {
  58.             //ignore
  59.         }
  60.         synchronized (pool) {
  61.             if (!pool.isEmpty()) {
  62.                 //Connection conn = pool.keySet().iterator().next();// fetch last connection for ever
  63.                  Connection conn=(Connection)pool.keySet().toArray()[RandomUtil.getRandomNum(pool.size())]; //random fetch one connection
  64.                 pool.remove(conn);
  65.                 try {
  66.                     conn.setAutoCommit(true);
  67.                 } catch (SQLException e) {
  68.                     pool.clear();
  69.                     conn = getConnection();
  70.                 }
  71.                 return getProxyConnection(conn);
  72.             }
  73.         }
  74.         //System.out.println(url);
  75.         //System.out.println(username+":"+password);
  76.         //return DriverManager.getConnection("jdbc:mysql://10.204.79.234:3306/library?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8",username,password);
  77.          
  78.         //url = "jdbc:mysql://10.204.79.234:3306/library?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8";
  79.         return getProxyConnection(DriverManager.getConnection(url,username,password));
  80.     }

  81.     private Connection getProxyConnection(Connection connection) {
  82.         final Connection conn = connection;
  83.         InvocationHandler handler = new InvocationHandler() {
  84.             public Object invoke(Object proxy, Method method, Object[] params) throws Exception {
  85.                 Object ret = null;
  86.                 if ("close".equals(method.getName())) {
  87.                     close(conn);
  88.                 } else {
  89.                     ret = method.invoke(conn, params);
  90.                 }
  91.                 return ret;
  92.             }
  93.         };
  94.         return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[] { Connection.class }, handler);
  95.     }

  96.     public String getUrl() {
  97.         return url;
  98.     }

  99.     public void setUrl(String url) {
  100.         this.url = url;
  101.     }

  102.     public String getUsername() {
  103.         return username;
  104.     }

  105.     public void setUsername(String username) {
  106.         this.username = username;
  107.     }

  108.     public String getPassword() {
  109.         return password;
  110.     }

  111.     public void setPassword(String password) {
  112.         this.password = password;
  113.     }

  114.     public int getMinSize() {
  115.         return minSize;
  116.     }

  117.     public void setMinSize(int minSize) {
  118.         this.minSize = minSize;
  119.     }

  120.     public int getMaxSize() {
  121.         return maxSize;
  122.     }

  123.     public void setMaxSize(int maxSize) {
  124.         semaphore=new Semaphore(maxSize,false);
  125.         this.maxSize = maxSize;
  126.     }

  127.     public String getDriverClass() {
  128.         return driverClass;
  129.     }

  130.     public void setDriverClass(String driverClass) {
  131.         try {
  132.             Class.forName(driverClass);
  133.         } catch (ClassNotFoundException e) {
  134.             log.error(driverClass+" not exists.");
  135.             throw new DataSourceException(driverClass+" not exists.",e);
  136.         }
  137.         this.driverClass = driverClass;
  138.     }

  139.     @Override
  140.     public PrintWriter getLogWriter() throws SQLException {
  141.         // TODO Auto-generated method stub
  142.         return null;
  143.     }

  144.     @Override
  145.     public int getLoginTimeout() throws SQLException {
  146.         // TODO Auto-generated method stub
  147.         return 0;
  148.     }

  149.     @Override
  150.     public java.util.logging.Logger getParentLogger()
  151.             throws SQLFeatureNotSupportedException {
  152.         // TODO Auto-generated method stub
  153.         return null;
  154.     }

  155.     @Override
  156.     public void setLogWriter(PrintWriter arg0) throws SQLException {
  157.         // TODO Auto-generated method stub
  158.          
  159.     }

  160.     @Override
  161.     public void setLoginTimeout(int arg0) throws SQLException {
  162.         // TODO Auto-generated method stub
  163.          
  164.     }

  165.     @Override
  166.     public boolean isWrapperFor(Class<?> arg0) throws SQLException {
  167.         // TODO Auto-generated method stub
  168.         return false;
  169.     }

  170.     @Override
  171.     public <T> T unwrap(Class<T> arg0) throws SQLException {
  172.         // TODO Auto-generated method stub
  173.         return null;
  174.     }

  175.     @Override
  176.     public Connection getConnection(String arg0, String arg1)
  177.             throws SQLException {
  178.         // TODO Auto-generated method stub
  179.         return null;
  180.     }
  181. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP