java - 在 Struts2 中维护多个 JDBC 连接

标签 java jdbc jboss struts2 jndi

数据库连接数超出允许的限制。

这是我迄今为止尝试过的。

当用户成功登录时,我向 session 添加一个连接对象:

Connection conn = DatabaseConnectionManager.getConnection();
sessionMap.put("Connection", conn);

然后,每当我需要数据库连接时,我都会从 session 中获取它:

Map<String, Object> sessionMap = (Map<String, Object>) ActionContext.getContext().get("session");
Connection conn = (Connection) sessionMap.get("Connection");

getConnection() 方法中,我打印调用该方法的次数。 那么,虽然我从 session 中获取 Connection 对象,但为什么连接数超出了允许的限制(50)?

JNDI 代码:

Connection conn = null;         
try {
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    DataSource ds = (DataSource) envCtx.lookup("jdbc/MySqdb");
    conn = ds.getConnection();

}  
catch (NamingException ex) {
    Logger.getLogger(DatabaseConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
}
catch (SQLException sqle) {
    sqle.printStackTrace();
}
System.out.println("connection: "+connection++);
return conn;

我使用过JNDI。连接数在允许的限度内。不知道这个方法是否正确,请指教。

最佳答案

每个用户一个连接根本不是一个好的解决方案。如前所述,您必须使用一些连接轮询,如果您想要简单的使用 https://commons.apache.org/proper/commons-dbcp/ 。 正如那里提到的:

Creating a new connection for each user can be time consuming (often requiring multiple seconds of clock time), in order to perform a database transaction that might take milliseconds. Opening a connection per user can be unfeasible in a publicly-hosted Internet application where the number of simultaneous users can be very large. Accordingly, developers often wish to share a "pool" of open connections between all of the application's current users. The number of users actually performing a request at any given time is usually a very small percentage of the total number of active users, and during request processing is the only time that a database connection is required. The application itself logs into the DBMS, and handles any user account issues internally.

您可以在 http://svn.apache.org/viewvc/commons/proper/dbcp/trunk/doc/ 找到示例

关于java - 在 Struts2 中维护多个 JDBC 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30257172/

相关文章:

java - 将数据从 SQL Server 传输到 Hadoop

java - JSF FacesTagExtraInfo 类不在 JSF 1.2 v 中

java - XCUI测试: How to fetch List of elements from the iOS screen

jdbc - 如何使用 clojure.jdbc 查询列表

java - 如何生成 UTC 格式的 java.sql.Timestamp 用于查询比较?

Java JDBC 延迟加载的结果集

java - hibernate 默认采用哪种命名策略

java - EJB 和在数据结构(映射、列表等)中存储对象

java - java中同时min和minindex的内置函数?

Java Swing : how to customize the JList's items?