【发布时间】:2015-08-13 21:21:04
【问题描述】:
我正在使用数据库(特别是 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>
那么我怎样才能减少获得数据库连接所需的时间呢?我已经在使用连接池机制了。我想到的唯一解决方案是使资源类成为单例并获得一次连接,但是当需要处理许多请求时,这似乎违反直觉。
【问题讨论】:
-
您的观察是否针对大量请求?如果仅针对一个(尤其是第一个)请求做出分析结论,那么对于多种因素来说这有点没有意义。
-
我重复了几次测试。时间各不相同,但总体而言,getConnection 调用总是花费大部分时间。
标签: database rest jakarta-ee cxf apache-tomee