JavaServlet封装一个druid数据连接池,并优化使连接池效率最优抗并发

渡星河
2023-02-16 / 0 评论 / 9 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年02月16日,已超过581天没有更新,若内容或图片失效,请留言反馈。

Druid 是阿里巴巴开源的一款高性能的 JDBC 连接池,在 Java Web 开发中被广泛使用。要封装一个 Druid 数据连接池,可以按照以下步骤进行:

  1. 引入 Druid 和数据库驱动的依赖。
    在 Maven 中添加以下依赖:

    <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
     <version>1.2.6</version>
    </dependency>
    <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>8.0.27</version>
    </dependency>
    
  2. 创建 Druid 数据源对象。
    在 ServletContextListener 中创建 Druid 数据源对象,将其设置为全局变量,这样在整个应用程序中都可以共享该数据源。

    @WebListener
    public class ContextListener implements ServletContextListener {
     
     @Override
     public void contextInitialized(ServletContextEvent sce) {
         ServletContext servletContext = sce.getServletContext();
         String jdbcUrl = "jdbc:mysql://localhost:3306/test";
         String username = "root";
         String password = "password";
         DataSource dataSource = createDataSource(jdbcUrl, username, password);
         servletContext.setAttribute("dataSource", dataSource);
     }
    
     @Override
     public void contextDestroyed(ServletContextEvent sce) {
         // do nothing
     }
    
     private DataSource createDataSource(String jdbcUrl, String username, String password) {
         DruidDataSource dataSource = new DruidDataSource();
         dataSource.setUrl(jdbcUrl);
         dataSource.setUsername(username);
         dataSource.setPassword(password);
         dataSource.setInitialSize(5); // 初始化连接池大小
         dataSource.setMinIdle(5); // 最小空闲连接数
         dataSource.setMaxActive(100); // 最大连接数
         dataSource.setMaxWait(60000); // 获取连接的最长等待时间
         dataSource.setValidationQuery("SELECT 1"); // 检测连接是否有效的 SQL
         dataSource.setTestOnBorrow(true); // 获取连接时检测是否有效
         dataSource.setTestOnReturn(false); // 归还连接时不检测是否有效
         dataSource.setTestWhileIdle(true); // 定时检测空闲连接是否有效
         dataSource.setTimeBetweenEvictionRunsMillis(60000); // 定时检测的时间间隔
         dataSource.setMinEvictableIdleTimeMillis(300000); // 空闲连接超过该时间会被回收
         dataSource.setMaxEvictableIdleTimeMillis(600000); // 空闲连接最长存活时间
         return dataSource;
     }
    }

    上面的代码中,我们在 contextInitialized() 方法中创建了 Druid 数据源对象,并将其设置为 ServletContext 中的属性。在创建数据源时,我们指定了一些参数,例如最大连接数、初始化连接池大小、最长等待时间等。

  3. 在 Servlet 中获取 Druid 数据源对象,并从数据源中获取数据库连接。
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DataSource dataSource = (DataSource) getServletContext().getAttribute("dataSource");
        try (Connection conn = dataSource.getConnection()) {
            // 使用连接进行数据库操作
        } catch (SQLException e) {
          
        }
      }
}
0

评论 (0)

取消