簡體   English   中英

縮短RESTful響應時間

[英]Improve RESTful response time

我正在使用使用數據庫(特別是postgres)的TomEE +(Apache CXF)在Java EE中實現RESTful服務。 現在,我注意到函數中最長的時間花在了數據庫的getConnection()調用上。

我的代碼如下所示:

import java.sql.Connection;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/test")
public class TestResource {

    /* external DB resource
     * configured in the resources.xml as "testDB". Either match the
     * name or use the name parameter of the resource annotation.
     */
    @Resource private DataSource testDB;

    @Path("/hello")
    @GET
    @Produces("text/plain")
    public String test() throws SQLException
    {
        Connection conn = testDB.getConnection(); //majority of time is spent in here
    /*
      do something.(e.g. PreparedStatement ps = conn.prepareStatement(...)
    */

        conn.close();
        return "world";
    }
}

像這樣在resources.xml中定義數據庫:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <Resource id="testDB" type="javax.sql.DataSource">
    accessToUnderlyingConnectionAllowed = false
    connectionProperties = 
    defaultAutoCommit = true
    defaultReadOnly = 
    definition = 
    ignoreDefaultValues = false
    initialSize = 0
    jdbcDriver = org.postgresql.Driver
    jdbcUrl = jdbc:postgresql://localhost/testdb
    jtaManaged = true
    maxActive = 100
    maxIdle = 20
    maxOpenPreparedStatements = 0
    maxWaitTime = 100 millisecond
    minEvictableIdleTime = 30 minutes
    minIdle = 0
    numTestsPerEvictionRun = 3
    password = password
    passwordCipher = PlainText
    poolPreparedStatements = false
    serviceId = 
    testOnBorrow = true
    testOnReturn = false
    testWhileIdle = false
    timeBetweenEvictionRuns = -1 millisecond
    userName = user
    validationQuery = SELECT 1;
    removeAbandoned = true
    removeAbandonedTimeout = 60
    logAbandoned = true

</Resource>
</resources>

那么,如何減少建立數據庫連接所花費的時間呢? 我已經在使用連接池機制。 我想到的唯一解決方案是使資源類成為單例並獲得一次連接,但是當需要處理許多請求時,這似乎違反直覺。

我通常希望與數據庫的交互是該過程中最慢的部分。 我想知道數據庫調用要增加多少開銷? 與通過Java代碼外部的SQL工具進行數據庫調用相比,這有什么關系。

另外-我不確定示例是否只是為了簡潔起見,但我將嘗試對解決方案進行分層,以便初始層處理路由和驗證,而下一層處理任何業務邏輯並與數據庫(DAO)層進行交互。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM