`

数据库连接池的实现(含等待处理)

阅读更多
这是一个数据库连接池实现的例子,简单实现,含连接等待处理。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import org.lt.cj.config.ServerProperty;

//代理连接类
public class MyDataSource {

    private static MyDataSource instance = new MyDataSource();
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://127.0.0.1:3306/tmall";
    private static String user = "root";
    private static String password = "123456";
    private static int initCount = 3; // 初始化连接数
    private static int maxCount = 10; // 最大连接数
    private static int timeout = 100; //连接用完后再次获取连接间隔时间(毫秒)
    int currentCount = 0; // 当前连接数
    // LinkedList方便入列出列操作,性能比ArrayList好
    private final LinkedList<Connection> connectionsPool = new LinkedList<Connection>();

    public MyDataSource() {
        try {
            for (int i = 0; i < this.initCount; i++) {
                // 把初始化的连接对象存放到链表里面
                this.connectionsPool.addLast(this.createConnection());
                this.currentCount++;
            }
        } catch (SQLException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static MyDataSource getInstance() {
        return instance;
    }

    //静态内部类在没有新建对象的情况下也可以加载
    static {
        ServerProperty sp = new ServerProperty();
        driver = sp.getValue("driver");
        url = sp.getValue("databaseUrl");
        user = sp.getValue("username");
        password = sp.getValue("password");
        initCount = Integer.parseInt(sp.getValue("initCount"));
        maxCount = Integer.parseInt(sp.getValue("maxCount"));
        timeout = Integer.parseInt(sp.getValue("timeout"));
        sp.closeI();

        try {
            Class.forName(driver);// 加载驱动程序,供调用,只执行一次
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public Connection getConnection() {
        synchronized (connectionsPool) {
            if (this.connectionsPool.size() > 0) { // 从链表里面删除头一个连接对象,并返回该连接对象
                return this.connectionsPool.removeFirst();
            }
            if (this.currentCount < maxCount) {
                try {
                    this.currentCount++;
                    return this.createConnection();
                } catch (SQLException ex) {
                    return null;  //无法创建连接,返回空
                }
            }
            return getConnection(timeout);
        }
    }

    /**
     *   根据指定延时取得一个连接
     */
    public synchronized Connection getConnection(long timeout) {
        Connection con = null;
        while ((con = getConnection()) == null) {
            try {
                Thread.sleep(timeout);
            } catch (InterruptedException e) {
            }
        }
        return con;
    }

    // 释放连接,把当前连接加到链表尾,并没有真正关闭
    public void free(Connection conn) {
        synchronized (connectionsPool) {
            this.connectionsPool.addLast(conn);
        }
    }

    // 父类引用指向子类对象,生成一个实现对象供使用
    private Connection createConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
}



配置文件读取类:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ServerProperty {

    private Properties prop = null;
    private InputStream in = null;

    public ServerProperty() {
        initProperty();
    }

    public ServerProperty(String path) {
        try {
            prop = new Properties();
            in = new FileInputStream(path);
        } catch (FileNotFoundException ex) {
        }
    }

    private void initProperty() {
        try {
            prop = new Properties();
            in = new FileInputStream("conf/database.properties");
        } catch (FileNotFoundException ex) {
        }
    }

    private void setIs() {
        try {
            if (in == null) {
                in = new FileInputStream("conf/database.properties");
            }
        } catch (IOException ex) {
        }
    }

    public Properties getProperty() {
        try {
            setIs();
            prop.load(in);
        } catch (IOException ex) {
        }
        return prop;
    }

    public String getValue(String key) {
        String value = "";
        try {
            setIs();
            prop.load(in);
            value = prop.getProperty(key);
        } catch (IOException ex) {
        }
        return value;
    }

    public void closeI() {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
        }
    }
}



工程项目目录下的文件:conf/database.properties
内容:
#Oracle config#
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@192.168.0.23:1521:ora10g
#user=openlab
#password=open123

#Mysql config#
driver=com.mysql.jdbc.Driver
databaseUrl=jdbc:mysql://127.0.0.1:3306/tmall
username=root
password=123456
#初始连接数
initCount=3
#最大连接数
maxCount=20
#连接用完后再次获取连接间隔时间(毫秒)
timeout=100


调用:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class CollectImpl implements ICollectDao {

    private static final MyDataSource ds = new MyDataSource();
    private static Connection conn = null;

    public Connection getConnection() {
        return (Connection) ds.getConnection(); 
    }

    //释放操作
    public void closePsRs(PreparedStatement ps, ResultSet rs) {
        try {
            if (ps != null) {
                ps.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException ex) {
        }
    }

    public void free(Connection conn) {
        ds.free(conn);
    }

    //对分类表进行操作
    public void insertCategory(String name, int firstCate, int secondCate, String lanFrom, String toLan, int updated) {
        conn = getConnection();
        System.out.println("---------" + conn);
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "INSERT INTO `" + lanFrom + "_category` (`name`,`first_cate`,`second_cate`,`orig_lan`,`to_lan`,`updated`) VALUES(?,?,?,?,?,?)";
        try {
            ps = (PreparedStatement) conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setInt(2, firstCate);
            ps.setInt(3, secondCate);
            ps.setString(4, lanFrom);
            ps.setString(5, toLan);
            ps.setInt(6, updated);
            ps.executeUpdate();
        } catch (SQLException ex) {
        } finally {
            closePsRs(ps, rs);
            free(conn);
        }
    }
}

分享到:
评论

相关推荐

    基于C++实现多线程连接池MySQL源码+项目说明+详细代码注释.zip

    * 数据库连接池对应C++中的一个数据库连接对象,即`单例模式` * 连接池中包括数据库服务器连接对应的IP,端口,用户,密码等信息 * 对数据库对象存入`STL`当中,需要设置最大值,最小值限制队列 * 多线程从连接池中...

    数据库设计准则及方法论.docx

    对于同一套数据库逻辑设计,不同的数据库产品有不同的实现方法,下面的表格列出了不同数据库产品的实现技术。 逻辑架构 实现技术 对称多处理器(SMP) 基本所有商业数据库都支持 Sharing Nothing架构(多分区数据库) ...

    mysql数据库my.cnf配置文件

    可以实现单表在不同的数据库中移动。 # 4.空间可以回收(除drop table操作处,表空不能自已回收) # 缺点: # 单表增加过大,如超过100G # 结论: # 共享表空间在Insert操作上少有优势。其它都没独立表空间表现好。...

    基于springboot , zookeeper , redis 分布式事务强一致性方案+源代码+文档说明

    # 连接池最大阻塞等待时间(使用负值表示没有限制) fat.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 fat.redis.pool.max-idle=10 # 连接池中的最小空闲连接 fat.redis.pool.min-idle=2 # 连接超时时间(毫秒...

    JAVA上百实例源码以及开源项目

    百度云盘分享 ... Java实现的FTP连接与数据浏览程序,实现实例化可操作的窗口。  部分源代码摘录:  ftpClient = new FtpClient(); //实例化FtpClient对象  String serverAddr=jtfServer.getText();...

    医院信息系统(临床诊疗、药品管理、财务管理、患者管理)

    Druid 1.1.10 数据库连接池 OSS 2.5.0 对象存储 JWT 0.9.1 跨域身份验证解决方案 Lombok 1.18.6 简化对象封装工具 Junit 4.12 单元测试框架 Logback 1.2.3 日志框架 Java doc ———— API帮助文档 Docker 18.09.6 ...

    JAVA上百实例源码以及开源项目源代码

     Java实现的FTP连接与数据浏览程序,实现实例化可操作的窗口。  部分源代码摘录:  ftpClient = new FtpClient(); //实例化FtpClient对象  String serverAddr=jtfServer.getText(); //得到服务器地址  ...

    【分布式事务----LCN】LCN原理及使用方式.docx

    TxClient的代理连接池实现了javax.sql.DataSource接口,并重写了close方法,事务模块在提交关闭以后TxClient连接池将执行"假关闭"操作,等待TxManager协调完成事务以后在关闭连接。 对于代理连接池的优化 自动超时...

    java面试题

    wait()是Object类的方法,对此对象调用了wait方法导致本线程放弃对象锁,进入等待锁定池,只有针对此对象发出notify方法后本线程才进入对象锁定池准备获得对象锁进入运行状态。 同步和异步,在什么情况下分别使用? ...

    超级有影响力霸气的Java面试题大全文档

    wait是Object类的方法,对此对象调用wait方法导致本线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象发出notify方法(或notifyAll)后本线程才进入对象锁定池准备获得对象锁进入运行状态。 17、...

    Java开发技术大全 电子版

    8.3.3使用isAlive()和join()等待子线程结束273 8.3.4设置线程优先级275 8.4线程的通信与协调277 8.4.1线程的互斥277 8.4.2线程的同步279 8.4.3暂停、恢复和停止线程282 8.4.4生产者-消费者问题实例284 8.5本...

    oracle学习文档 笔记 全面 深刻 详细 通俗易懂 doc word格式 清晰 连接字符串

    说明:用于连接到oracle数据库,也可实现用户的切换 用法:conn 用户名/密码 [as sysdba/sysoper] 注意:当用特权用户连接时,必须带上sysdba或sysoper 例子: 3. 断开连接(disc) 说明:断开与当前数据库的连接 ...

    Redis的.net客户端StackExchange.Redis.zip

    没有连接池自然有其利弊,最大的好处在于等待获取连接的等待时间没有了,也不会因为连接池里面的连接由于没有正确释放等原因导致无限等待而处于死锁状态。缺点在于一些低质量的代码可能导致服务器资源耗尽。不过提供...

    Java并发编程(学习笔记).xmind

    (2)实现资源池,例如数据库连接池 (3)使用信号量将任何一种容器变成有界阻塞容器 栅栏 能够阻塞一组线程直到某个事件发生 栅栏和闭锁的区别 所有线程必须同时到达栅栏位置,...

    百度地图毕业设计源码-ymdx-concurrency:义码当仙之并发编程

    百度地图毕业设计源码 义码当仙之并发编程 一、多线程基础 示例项目:concurrency01-thread-basis 进程与线程 每个正在系统上运行的...数据库连接池 迅雷下载 此时采用多线程,只能提高下载效率,并不能提高下载速度

    Java范例开发大全 (源程序)

     第4章 异常处理(教学视频:62分钟) 54  4.1 编译时异常 54  实例35 除0发生的算术异常(ArithmeticException) 54  实例36 数组下标越界异常(ArrayIndexOutOfBoundsException) 55  实例37 数组元素...

Global site tag (gtag.js) - Google Analytics