2014-09-01 40 views
0

我想重新使用一個java.sql.Connection對象。這是與谷歌App Engine,所以連接池不是一種選擇(我認爲?)。通常我只是爲每個servlet調用創建一個新的連接,但是現在我已經從servlet調用了函數,並且我不想在每個函數調用上創建一個新連接(除非我知道它會非常快),例如有沒有辦法在Java App Engine中重新使用MySQL Db連接

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對象?

回答

1

在App Engine中,前端被認爲是爲web請求提供服務,部分設計是它可以在實例間移動,刪除或根據需要啓動。這意味着您的連接對象在您的Servlet中使用其他方法時可能無效。

正如你可以使用數據存儲,你不需要建立連接或谷歌雲SQL

在另一方面,如果你需要這麼多使用自己的MySQL替代方案,你可以保持連接活躍在模塊[1]中,可能比前端請求長。作爲一個例子,您可以將任務添加到拉隊列中,並且該模塊會在保持連接的同時從中消耗下一個任務。

在這種情況下,響應速度不會像使用數據存儲一樣快。

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

+0

感謝您的回覆。我只需要在單個請求期間重新使用連接,儘管如我的代碼段所示。 – Floris 2014-09-01 15:28:45

+0

爲什麼不將它分配給可從任何方法訪問的本地類變量? – Mario 2014-09-01 15:49:31

相關問題