【问题标题】:Is there a way to re-use the MySQL Db connection in Java App Engine有没有办法在 Java App Engine 中重用 MySQL Db 连接
【发布时间】:2014-09-01 11:50:07
【问题描述】:

我想重用 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 对象?

【问题讨论】:

    标签: java sql google-app-engine connection


    【解决方案1】:

    在 App Engine 中,前端被认为是为 Web 请求提供服务,设计的一部分是它能够根据需要在实例之间移动、删除或启动。这意味着当从 Servlet 中的其他方法使用时,您的连接对象可能无效。

    作为替代方案,您可以在不需要设置连接的地方使用 Datastore 或 Google Cloud SQL

    另一方面,如果您非常需要它来使用自己的 MySQL,您可以在一个模块 [1] 中保持连接活动,该模块可能比前端请求的寿命更长。例如,您可以将任务添加到拉取队列中,该模块将使用其中的下一个任务,同时保持连接。

    在这种情况下,响应速度不会像使用 Datastore 一样快。

    [1] App Engine 模块 - https://developers.google.com/appengine/docs/java/modules/

    【讨论】:

    • 感谢您的回复。尽管如我的代码 sn-p 所示,我只需要在单个请求期间重新使用连接。
    • 为什么不将它分配给一个可以从任何方法访问的局部类变量?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 2020-09-22
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多