Home Database Mysql Tutorial JDBC连接池的简单实现

JDBC连接池的简单实现

Jun 07, 2016 pm 03:58 PM
android jdbc one time accomplish Simple illustrate connect

先说明一下,我本身是做android开发的,java web是我的弱项,只是近来京东云免费,于是去折腾了几下,有了些许经验,特作分享。如果文章中内容有误,还请各高手指正。 我在web端,需要连接数据库进行查询插入等操作,但是每次进行操作都先获取连接用完后就断

先说明一下,我本身是做android开发的,java web是我的弱项,只是近来京东云免费,于是去折腾了几下,有了些许经验,特作分享。如果文章中内容有误,还请各高手指正。

我在web端,需要连接数据库进行查询插入等操作,但是每次进行操作都先获取连接用完后就断开的话,未免效率太低。以前知道tomcat中可以配置,但是京东云引擎的tomcat并不能由自己配置。因为我折腾的东西较小,所以也不考虑使用框架,于是就想自己写一个。

我写的连接池很简单,在初始化时创建5个连接,并放在一个列表当中。如果要获取连接,从列表中获取,同时列表移除,还回来时,列表添加上。也就是列表保存的是闲置的连接。

如果列表已经为空了,那么判断是否超过最大连接了,没有就创建,有的话就等待。当然,我这里做的是很简单的实现,所以没有去做等待超时等处理。

代码如下:

package com.githang.tucao.web.dbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

public class DatabaseConnection {
    private static final String CREATE_TABLE_TWITTER = "CREATE TABLE IF NOT EXISTS twitter (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, msg varchar(300) not null) DEFAULT CHARSET=utf8";
    final static String HOST = "host";
    final static String PORT = "port";
    final static String DB_NAME = "dbname";
    final static String USERNAME = "username";
    final static String PASSWORD = "password";
    final static String url = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DB_NAME
            + "?useUnicode=true&characterEncoding=utf-8";
    private static final DatabaseConnection instance = new DatabaseConnection();
    private final int INIT_COUNT = 5;
    private final int MAX_COUNT = 30;
    private int count = 0;
    
    private final Object wait = new Object();
    
    private  LinkedList<Connection> CONN_POOL;

    private DatabaseConnection() {
        CONN_POOL = new LinkedList<Connection>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            for (int i = 0; i < INIT_COUNT; i++) {
                Connection connection = createConnection();
                if(connection != null) {
                    CONN_POOL.add(createConnection());
                    count++;
                }
            }
     //       Connection connection = getConnection();
     //       Statement stmt = connection.createStatement();
     //       stmt.execute(CREATE_TABLE_TWITTER);
     //       stmt.execute("set names &#39;utf-8&#39;");
     //       stmt.close();
     //       releaseConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static DatabaseConnection getInstance() {
        return instance;
    }
    
    private static Connection createConnection() {
        try {
            return DriverManager.getConnection(url, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Connection getConnection() {
        synchronized (CONN_POOL) {
            while(CONN_POOL.size() > 0) {
                Connection conn = CONN_POOL.removeLast();
                try {
                    if(conn.isValid(1000)) {
                        return conn;
                    } else {
                        count--;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(count < MAX_COUNT) {
                count++;
                return createConnection();
            } 
            synchronized (wait) {
                try {
                    wait.wait(3000);
                    if(CONN_POOL.size() > 0) {
                        return CONN_POOL.removeLast();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public void releaseConnection(Connection connection) {
        CONN_POOL.add(connection);
        synchronized (wait) {
            wait.notify();
        }
    }
    
}
Copy after login
其中count用于保存当前连接数(包括闲置和在使用的)。

wait对象用于线程同步锁,主要是获取不到连接并且需要等其他连接被还回来时使用,在getConnection()里面调用 wait,而在releaseConnection()方法中,也就是释放连接时,调用 notify通知其他等待的线程。

另外,在公用的数据库当中,数据库连接通常是不作长连接的。所以在这里连接池中的连接,可能是已经断开的或者是无效的,所以在获取连接时需要判断一下当前拿到的连接是否还有效。没有的话就拿下一个。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship Sep 10, 2024 am 06:45 AM

OnePlus'sister brand iQOO has a 2023-4 product cycle that might be nearlyover; nevertheless, the brand has declared that it is not done with itsZ9series just yet. Its final, and possibly highest-end,Turbo+variant has just beenannouncedas predicted. T

See all articles