繁体   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