改善RESTful响应时间

时间:2015-08-13 21:21:04

标签: database rest java-ee cxf tomee

我正在使用TomEE +(Apache CXF)在Java EE中实现RESTful服务,它使用数据库(特别是postgres)。现在我注意到我的函数中最长的时间花在数据库的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>

那么我怎样才能减少获取数据库连接所需的时间?我已经在使用连接池机制了。我想到的唯一解决方案是使资源类成为单例并获得一次连接,但是当需要处理许多请求时,这似乎是违反直觉的。

1 个答案:

答案 0 :(得分:0)

我通常希望与数据库的交互是该过程中最慢的部分。我有兴趣知道数据库调用添加了多少开销?这与通过Java代码之外的SQL工具进行数据库调用有什么关系。

此外 - 我不确定该示例是否仅仅是为了简洁,但我会尝试对您的解决方案进行分层,以便初始层处理路由和验证,而下一层处理任何业务逻辑并与数据库交互( DAO)层。

相关问题