JAVA笔记概览 - 简单模拟连接池

本文介绍了一个简单的数据库连接池实现方式,通过模拟的方式展示了如何管理多个数据库连接,包括连接的获取、使用及归还过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模拟连接池

简单模拟连接池的实现, 不考虑线程安全等, 只为了解原理

配置文件 server.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3310/java_jdbc_test?useSSL=false
user=root
password=root

数据库连接

package com.gugudu.pool.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

/**
 * 
 * 封装数据库连接
 * 
 * @author hui
 *
 */
public class DBUtils {

    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    static {

        ResourceBundle rb = ResourceBundle.getBundle("server");
        driver = rb.getString("driver");
        url = rb.getString("url");
        user = rb.getString("user");
        password = rb.getString("password");

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     * @return Connection conn
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    /**
     * 关闭资源
     * @param ResultSet rs
     * @param Statement stmt
     * @param Connection conn
     * @throws SQLException
     */
    public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }   
}

连接池

package com.gugudu.pool.utils;

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

/**
 * 
 * 模拟数据库连接池, 模拟而已
 * 
 * @author hui
 *
 */
public class SimpleConnectionPool {

    private static final int MAX_CONNECTION = 10;
    // 1. 创建一个存放连接的池 
    private static LinkedList<Connection> pool = new LinkedList<Connection>();

    // 2. 初始化 连接
    static {
        for (int i = 0; i < MAX_CONNECTION; i++) {
            try {
//                System.out.println("初始化连接成功: NO." + (i+1));
                pool.add(DBUtils.getConnection());
            } catch (SQLException e) {
                throw new ExceptionInInitializerError("初始化数据库连接失败, 请检查配置");
            }
        }
    }

    // 3. 获取一个连接
    public static Connection getConnectionFromPool() {
        if (pool.size() > 0) {
            return pool.removeFirst();
        } else {
            // 等待
            try {
                System.out.println("等待连接...");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (pool.size() > 0) {
                return pool.removeFirst();
            }
            // 超时创建一个临时连接 记得要 close
            throw new RuntimeException("服务器忙...");
        }
    }

    // 4. 释放资源(连接放回连接池)
    public static void release(Connection conn) {
        if (conn instanceof Connection) {
            pool.addLast(conn);
        }
    }

    // 获取当前剩余连接数
    public static int currentConnections() {
        if (pool != null) {
            return pool.size();
        }
        return 0;
    }
}

测试

package com.gugudu.pool;

import java.sql.Connection;


import com.gugudu.pool.utils.SimpleConnectionPool;

public class Demo01 {

    public static void main(String[] args) {

        System.out.println("当前剩余连接数: " + SimpleConnectionPool.currentConnections());

        Runnable r = new My();

        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            new Thread(r).start();
        }

    }

}


class My implements Runnable {

    @Override
    public void run() {

        Connection conn = SimpleConnectionPool.getConnectionFromPool();

        System.out.print(Thread.currentThread().getName() + " == ");
        System.out.println("当前剩余连接数: " + SimpleConnectionPool.currentConnections());

        try {
            // 模拟数据处理阻塞
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SimpleConnectionPool.release(conn);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值