数据库连接数超出允许的限制。
这是我迄今为止尝试过的。
当用户成功登录时,我向 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/