I want to re-use a java.sql.Connection
object. It is with Google App Engine so connection pooling is not an option (I think?). Normally I just create a new connection per servlet call, but now I have functions being called from the servlet and I don't want to create a new connection on each function call (unless I know it will be very fast), eg
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;
}
}
How can I re-use the Connection
object of the servlet within someSQLFunction()
?
In App Engine, the front end is thought to serve web requests, and part of the design is its ability to be moved among instances, deleted or started as needed. That means that your connection object could be invalid when used from another method in your Servlet.
As an alternative you could use Datastore where you don't need to set up connections or Google Cloud SQL
On the other hand, if you need it so much to use your own MySQL, you could keep the connection alive in a module [1] that may outlive front-end requests. As an example you could add tasks to a pull queue, and the module would consume the nexts tasks from it, while keeping the connection.
In this case, the response speed wouldn't be as fast as using Datastore.
[1] App Engine Modules - https://developers.google.com/appengine/docs/java/modules/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.