使用 Druid 连接池配置和获取数据库连接

首先,我们需要创建一个名为 druid.properties 的配置文件,该文件用于配置 Druid 连接池的相关属性。

druid.properties 文件内容

# 数据库连接URL
jdbc.url=jdbc:mysql://localhost:3306/mydb

# 数据库用户名
jdbc.username=root

# 数据库密码
jdbc.password=123456

# 数据库驱动类
jdbc.driver=com.mysql.jdbc.Driver

# 初始化连接数
initialSize=5

# 最小空闲连接数
minIdle=5

# 最大活跃连接数
maxActive=20

# 获取连接时最大等待时间,单位毫秒
maxWait=60000

# 配置用来检测连接是否有效的SQL语句
validationQuery=SELECT 1

# 连接检测的超时时间,单位秒
validationQueryTimeout=5

# 是否开启PSCache,默认为true
poolPreparedStatements=true

# 指定每个连接上PSCache的大小
maxPoolPreparedStatementPerConnectionSize=20

# 连接池中连接的最小生存时间,单位毫秒
minEvictableIdleTimeMillis=300000

# 连接池的清除扫描间隔,单位毫秒
timeBetweenEvictionRunsMillis=60000

# 连接池的连接空闲多久后释放,单位毫秒
minEvictableIdleTimeMillis=1800000

# 是否开启连接泄露检测,默认为false
removeAbandoned=false

# 连接泄露的检测时间,单位秒
removeAbandonedTimeout=180

# 是否开启自动提交事务,默认为true
defaultAutoCommit=true

监听器代码

import com.alibaba.druid.pool.DruidDataSource;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Connection;
import java.sql.SQLException;

@WebListener
public class DruidListener implements ServletContextListener {
    private DruidDataSource dataSource;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 初始化Druid连接池
        dataSource = new DruidDataSource();
        dataSource.setUrl('jdbc:mysql://localhost:3306/mydb');
        dataSource.setUsername('root');
        dataSource.setPassword('123456');

        try {
            dataSource.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // 关闭Druid连接池
        dataSource.close();
    }

    public Connection getConnection() throws SQLException {
        // 获取数据库连接
        return dataSource.getConnection();
    }
}

Servlet 代码

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet('/example')
public class ExampleServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取监听器中的数据库连接
        Connection connection = ((DruidListener) getServletContext().getAttribute('druidListener')).getConnection();

        try {
            // 执行数据库操作
            // ...
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭数据库连接
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

在上述代码中,我们通过 getServletContext().getAttribute('druidListener') 来获取监听器的实例,并调用 getConnection() 方法来获取数据库连接。在执行完数据库操作后,我们需要手动关闭连接。

总结

通过以上步骤,我们成功配置了 Druid 连接池并通过监听器和 Servlet 获取数据库连接,方便进行数据库操作。需要注意的是,在使用完数据库连接后,需要及时关闭连接,避免资源泄漏。

使用 Druid 连接池配置和获取数据库连接

原文地址: https://www.cveoy.top/t/topic/qiBJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录