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

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

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

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

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

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. Python argparse模块实现模拟 linux 的ls命令

    python 模拟linux的 ls 命令 sample: python custom_ls.py -alh c:/ 选项: -a ,--all 显示所有文件,包括'.'开头的隐藏文件 -l  列表显 ...

  2. 关于如何获取移动端 touchmove 事件中真正触摸点下方的元素

    移动端的touchstart, touchmove, touchend三个事件,点击元素并拖动时,获取到了touchmove事件, 但是event.touches[0].target所指向的元素却是t ...

  3. Listview嵌套Listview

    今天做项目,打算模仿淘宝的订单管理,需要Listview嵌套Listview,都是两个控件都是沿着一个方向滑动的,嵌套在一起不幸福,以下是解决方案,打个笔记,以后估计还得用: 其中onMeasure函 ...

  4. 爬起点小说 day01

    先介绍下我自己爬起点小说的思路: 1.爬取所有的类型列表 a.链接存redis中 类型表:novel_list 具体每一种类型:bnovel_all_list(把novel_list和bnovel_l ...

  5. SpringMvc架构下css、js、jpg加载失败问题

    SpringMvc架构下css.js.jpg加载失败问题 springMvc搭建成功后,页面出现一些错误,jsp.js等静态资源加载失败.导致页面没有显示任何样式以及 此处原因很简单,是因为相对路径在 ...

  6. Mac关机时处于黑屏状态

    PS:不知道大家有没有遇到过mac电脑关机就黑屏,只有一个箭头,还可以滑动箭头,但就是黑屏状态,等个好长时间还是关不了机,因此我查了好多资料,原因是在关机时,mac要先关掉其他软件或者保存进程以备下次 ...

  7. 《Linux命令行与shell脚本编程大全》第二十六章 一些有意思的脚本

    26.1 发送消息 26.1.1 功能分析 1.确定系统中都有谁 $who 给出的信息包括用户名 用户所在终端 用户登入系统的时间 2.启用消息功能 用户可以禁止别人给我发消息,所以需要先检查一下是否 ...

  8. HDU 4556 Stern-Brocot Tree

    题意:求SB树第N层分母分子小于均等于N的数有多少? 搞清楚了SB Tree的性质,这道题就很容易了.因为SB Tree中的数均为最简分数,所以筛一波欧拉函数即可. #include<bits/ ...

  9. ssm整合(基于xml配置方式)

    本文是基于xml配置的方式来整合SpringMVC.Spring和Mybatis(基于注解的方式会再写一篇文章),步骤如下: (1)首先自然是依赖包的配置文件 pom.xml <project ...

  10. window.open()被拦截问题

    最近做项目的时候遇到一个需求,在商品详情页面中点击购买按钮,之后再新标签页中打开生成的订单页面,所以想用window.open()来实现.但是测试的时候发现打开的链接被浏览器拦截. 之后,开始在网上查 ...