我想重用java.sql.Connection
对象。它与 Google App Engine 一起使用,因此连接池不是一个选项(我认为?)。通常我只是为每个 servlet 调用创建一个新连接,但现在我有从 servlet 调用的函数,并且我不想在每个函数调用上创建一个新连接(除非我知道它会非常快),例如
public void someServlet() { // Called from web page - speed is thus of concern
try (Connection con = DriverManager.getConnection("connection string")) { // might be slow - want to re-use con
// Do something with connection, e.g. run some queries
someSQLFunction();
someSQLFunction();
someSQLFunction();
} catch (SQLException e) {
// Some error handling
}
}
public void someSQLFunction() throws SQLException {
// I don't want to re-create another Connection here, but use the one from the servlet.
try (Connection con = DriverManager.getConnection("connection string")) { // might be slow - want to re-use con
// Do something with connection, e.g. run some queries
return;
}
}
如何在 someSQLFunction()
中重用 servlet 的 Connection
对象?
最佳答案
在 App Engine 中,前端被认为是为 Web 请求提供服务,设计的一部分是其能够在实例之间移动、根据需要删除或启动。这意味着当从 Servlet 中的另一个方法使用时,您的连接对象可能无效。
作为替代方案,您可以使用数据存储区,无需设置连接或 Google Cloud SQL
另一方面,如果您非常需要使用自己的 MySQL,则可以在模块 [1] 中保持连接处于 Activity 状态,该模块可能比前端请求的生命周期更长。例如,您可以将任务添加到拉取队列中,模块将使用其中的下一个任务,同时保持连接。
在这种情况下,响应速度不会像使用数据存储那样快。
[1] App Engine 模块 - https://developers.google.com/appengine/docs/java/modules/
关于java - 有没有办法在 Java App Engine 中重用 MySQL Db 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25605241/