写得很蛋疼,本来想支持多线程的,奈何对多线程和连接池理解着实太菜;

所以,起码是能拿到连接了。。。

但是还是不太懂这个连接池

我也是半抄别人的,以后再搞一搞这个吧。

先是配置文件 理想是很丰满的,奈何现实。。。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=true
jdbc.username=root
jdbc.password=yck940522

#最小连接数
jdbc.minSize=
#最大连接数
jdbc.maxSize=
#初始化连接数
jdbc.initSize=
#重试次数
jdbc.tryTimes=
#延迟时间
jdbc.delay=
jdbc.maxActiveSize=
jdbc.timeOut=

jdbc.check = true
jdbc.checkTime = 

配了那么多参数,很多都没用上。。唉,还是太菜;

package jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class DataBase {
    private static String username;
    private static String password;
    private static String url;
    private static String driver;

    private static Integer minSize;
    private static Integer maxSize;
    private static Integer initSize;
    private static Integer maxActiveSize;
    private static Integer tryTimes;
    private static Long delay;
    private static Long timeOut;
    private static Boolean checked;
    private static Long checkTime;

    private static DataBase instance;

    private DataBase(){
        InputStream in = DataBase.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            username = p.getProperty("jdbc.username");
            password = p.getProperty("jdbc.password");
            url = p.getProperty("jdbc.url");
            driver = p.getProperty("jdbc.driver");
            minSize = Integer.valueOf(p.getProperty("jdbc.minSize","3"));
            maxSize = Integer.valueOf(p.getProperty("jdbc.maxSize","20"));
            initSize = Integer.valueOf(p.getProperty("jdbc.initSize","5"));
            maxActiveSize = Integer.valueOf(p.getProperty("jdbc.maxActiveSize","100"));
            tryTimes =Integer.valueOf(p.getProperty("jdbc.tryTimes","2"));
            delay = Long.valueOf(p.getProperty("jdbc.delay","1000"));
            timeOut = Long.valueOf(p.getProperty("jdbc.timeOut","1200000"));
            checked = Boolean.valueOf(p.getProperty("jdbc.check","false"));
            checkTime = Long.valueOf(p.getProperty("jdbc.checkTime","30000"));

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static DataBase getInstance(){
        if(instance == null){
            synchronized (DataBase.class){
                if(instance == null){
                    instance = new DataBase();
                }
            }
        }
        return instance;
    }

    public  String getUsername() {
        return username;
    }

    public  String getPassword() {
        return password;
    }

    public  String getUrl() {
        return url;
    }

    public  String getDriver() {
        return driver;
    }

    public  Integer getMinSize() {
        return minSize;
    }

    public  Integer getMaxSize() {
        return maxSize;
    }

    public  Integer getInitSize() {
        return initSize;
    }

    public  Integer getMaxActiveSize() {
        return maxActiveSize;
    }

    public  Integer getTryTimes() {
        return tryTimes;
    }

    public  Long getDelay() {
        return delay;
    }

    public  Long getTimeOut() {
        return timeOut;
    }

    public Boolean getChecked() {
        return checked;
    }

    public Long getCheckTime() {
        return checkTime;
    }
}

对单例也不太懂,瞎写,有经验的大佬指正一下啊

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;

public class ConnectionPool{

    private static final Long lazyTime = 30000L;

    private DataBase dataBase;
    private AtomicInteger totalSize = new AtomicInteger(0);
    private List<Connection> freeConnections = new Vector<Connection>();
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

    private static ConnectionPool  instance;

    private ConnectionPool(){
        this.dataBase = DataBase.getInstance();
        init();
    }

    public static ConnectionPool getInstance(){
        if(instance == null){
            synchronized (ConnectionPool.class){
                if(instance == null){
                    instance = new ConnectionPool();
                }
            }
        }
        return instance;
    }

    private void init(){
        try {
            Class.forName(dataBase.getDriver());
            for(int i=0;i<dataBase.getInitSize();i++){
                Connection connection = createConnection();
                freeConnections.add(connection);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private synchronized Connection createConnection(){
        try {
            Class.forName(dataBase.getDriver());
            Connection conn= DriverManager.getConnection(dataBase.getUrl(),dataBase.getUsername(),dataBase.getPassword());
            totalSize.incrementAndGet();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    private synchronized Connection getConnection() {
        Connection conn= null;
        try {
            if(totalSize.get() < dataBase.getMaxSize()){
                if(freeConnections.size()>0){
                    conn = freeConnections.get(0);
                    if(conn != null){
                        threadLocal.set(conn);
                    }
                    freeConnections.remove(0);
                }else {
                    conn = createConnection();
                }
            }else {
                wait(dataBase.getDelay());
                conn = getConnection();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return conn;
    }

    private boolean isValid(Connection conn){
        try {
            if(conn == null || conn.isClosed()){
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return true;
    }

    public synchronized Connection getCurrentConnection() {
        Connection conn = threadLocal.get();
        if(!isValid(conn)){
            return getConnection();
        }
        return conn;
    }

    public void checkPool() {
        if(dataBase.getChecked()){
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("空线池连接数:"+freeConnections.size());
                    System.out.println("总的连接数:"+totalSize.get());
                }
            }, lazyTime, dataBase.getCheckTime());
        }
    }

}

这个连接池我就不做什么说明了。。。自己只能理解最简单的。。。简单的说就是先初始化一部分连接放在一个list里,要用的时候就去取,如果没有超过上限也不用close了。。但是我一直没搞明白怎么去判断它空闲了多长时间然后close掉。。。所以很多也没实现。

大王让我写代码

2017-12-30

瞎j8封装第二版之数据库连接池的更多相关文章

  1. 瞎j8封装第二版之数据层的封装

    看了以前写的代码,对就是下面这个 手把手封装数据层之DataUtil数据库操作的封装 觉得以前写的代码好烂啊!!!,重新理了一下思路,写得更规范和简练,应该效率也会高很多,用了一下下午写的连接池(半废 ...

  2. 瞎j8封装第二版之用xml文件来代理dao接口

    也是重新整理了之前的那篇 模仿Mybatis用map per.xml实现Dao层接口的功能 话不多说直接上代码 首先是结构 依赖pom.xml <?xml version="1.0&q ...

  3. 一只菜鸟的瞎J8封装系列的目录

    因为这是一个系列...也就是我们所说的依赖关系.后面很多方法都是基于我前面封装的工具来进行的,所以我列一个目录供大家参考... 一只菜鸟的瞎J8封装系列  一.手把手封装数据层之DButil数据库连接 ...

  4. 计算器-- 利用re模块 利用函数封装 第二版

    import re remove_parentheses = re.compile('\([^()]+\)') def Remove_Parentheses(obj, s): # 找到内层的括号并且返 ...

  5. Java数据库连接池封装与用法

    Java数据库连接池封装与用法 修改于抄袭版本,那货写的有点BUG,两个类,一个用法 ConnectionPool类: package com.vl.sql; import java.sql.Conn ...

  6. 【数据库开发】如何创建MySQL数据库连接池(一个基于libmysql的MySQL数据库连接池示例(C/C++版))

      http://blog.csdn.net/horace20/article/details/8087557 1.  一般架构说明 图 1 架构层次图 一般应用系统数据库访问模块可大致分为两层,一层 ...

  7. 关于jdbc和数据库连接池的关系(不是封装的关系)

    你都说是数据库连接池了.那就是连接数据库用的.JDBC是java封装的对数据库的操作.当然你可以自己进一步封装.数据库连接池是JDBC使用的前提,如果连数据库连接池都没连上,JDBC的操作就谈不上了. ...

  8. java 数据库连接池 Oracle版

    首先应加入连接池和数据库连接的配置文件:数据库连接包:ojdbc6.jar数据库连接池包:commons-pool2-2.2.jar                       commons-dbc ...

  9. mongodb数据库连接池(java版)

    mongodb数据库接口的设计 package storm.db; import java.util.ArrayList; import com.mongodb.DB; import com.mong ...

随机推荐

  1. eclipse中Maven工程使用Tomcat7以上插件

    Maven中使用tomcat:run命令默认是使用Tomcat6的版本, 现在要用到Tomcat7以上的版本,在eclipse的Maven工程中配置如下 第一步:在项目的pom里面加入如下配置: 官网 ...

  2. apache编译安装 httpd 2.2 httpd 2.4

    #apache编译安装#httpd 2.2 , httpd 2.4 #!/bin/sh #apache编译安装 #httpd 2.2 , httpd 2.4 #centos #rpm -e httpd ...

  3. iOS 图片本地存储、本地获取、本地删除

    在iOS开发中.经常用到图片的本地化. iOS 图片本地存储.本地获取.本地删除,可以通过以下类方法实现. p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: ...

  4. Uncaught TypeError: download is not a function at HTMLAnchorElement.onclick (index.html:25)

    前段时间调试html报了这样的一个错误 Uncaught TypeError: download is not a function     at HTMLAnchorElement.onclick ...

  5. tomcat警告setting property 'debug' to '0' did not find a matching property

    在使用tomcat6.0版本结合myeclipse进行java web项目,运行程序显示setting property 'debug' to '0' did not find a matching ...

  6. NYOJ 138 找球号(二) bitset 二进制的妙用

    找球号(二) 时间限制:1000 ms  |  内存限制:65535 KB 难度:5 描述 描述 在某一国度里流行着一种游戏.游戏规则为:现有一堆球中,每个球上都有一个整数编号i(0<=i< ...

  7. php结合redis实现高并发下的抢购、秒杀功能 (转载)

    抢购.秒杀是如今很常见的一个应用场景,主要需要解决的问题有两个: 1 高并发对数据库产生的压力 2 竞争状态下如何解决库存的正确减少("超卖"问题) 对于第一个问题,已经很容易想到 ...

  8. PHP生成 uuid

    // 生成UUID,并去掉分割符 function guid() { if (function_exists('com_create_guid')){ $uuid = com_create_guid( ...

  9. C#自定义ip控件

    前言:由于项目中有ip输入,但C#中又没有IP控件,如果直接放4个TextBox感觉又怎么好,还不好控制,于是可以通过自定义控件的方式来解决,就又了下面的自定义ip控件,该控件功能基本完善,如果还有未 ...

  10. Linux正则表达式语法

    基本组成部分: 正则表达式的基本组成部分. 正则表达式 描述 示例 \ 转义符,将特殊字符进行转义,忽略其特殊意义 a\.b匹配a.b,但不能匹配ajb,.被转义为特殊意义 ^ 匹配行首,awk中,^ ...