繁体   English   中英

使用NetBeans在jsp tomcat中建立c3p0连接池

[英]c3p0 connection pooling in jsp tomcat with netbeans

我在jsp中执行连接池操作。 我在名为MCE_Server.java的特定类中创建了一个静态函数,并包含以下内容:

 public static void makeConnectionPool()
 {
    try
    {
        cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver");
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/mce_db");
        cpds.setUser("root");
        cpds.setPassword("xxxxxx");
        cpds.setMaxPoolSize(100);
        cpds.setMinPoolSize(10);
        cpds.setAcquireIncrement(20);
    } 
    catch (PropertyVetoException ex) 
    {

        Logger.getLogger(MCE_Server.class.getName()).log(Level.SEVERE, null, ex);
    }

 }

从jsp页面调用以下静态函数

http://................/dbActivatePage.jsp

我已包含功能的地方

      <%@page import="xxxxx.MCE_Server"%>
      <html>
      .
      .
      .
      <body>
      <%
              MCE_Server.makeConnectionPool();
      %>
      .
      .
      .
      </body>
      </html>

我计划按照MCE_Server.java中包含的静态函数来获取所需的Connection,如下所示:

       public static Connection getConnectionfromPool() throws SQLException
       {
             return cpds.getConnection();
       }

即每当我需要获得连接。 我将包含MCE_Server.getConnectionfromPool()

现在的问题是我收到错误

java.sql.SQLException: Connections could not be acquired from the underlying database!

为什么我得到这个......

关于进一步的试验和错误方法...。我发现代码cpds = new ComboPooledDataSource();下面的语句cpds = new ComboPooledDataSource(); 正在执行。

因此,这里可能是问题所在。 我的方法正确吗?

这不是一个好方法。 每当客户点击您的页面时,JSP的<%...%>中的内容就会执行。 每个Web应用程序只能创建一次连接池,而不是每个用户请求一次!

我最喜欢的在Web应用程序中设置连接池的方法是设置一个ServletContextListener,它在contextInitialized(ServletContextEvent sce)中创建该池,并将其绑定到应用程序范围内的名称(即,它设置ServletContext属性)。 。 池应该在ServletContextListener的contextDestroyed方法中关闭()。

如果这看起来工作量过多,则只需将makeConnectionPool()更改为私有方法,然后仅从静态初始化程序块内部调用即可。 摆脱<%MCE_Server.makeConnectionPool(); %>完全。 那么当MCE_Server类被加载时,makeConnectionPool()将仅被调用一次。 但是由于您从不破坏该池,因此,如果您卸载并热重新部署应用程序(即,在不退出Servlet容器的JVM的情况下修改并重新加载war文件),则会发现线程和其他资源的泄漏。

好吧,我们看一下显示的错误。

java.sql.SQLException: Connections could not be acquired from the underlying database!

尽管我同意Waldman使用ServletContextListener的想法,但您的c3p0配置似乎正确。 在您的情况下,我坚信问题必须与mysql类路径有关。 请检查您是否已正确包含mysql连接器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM