Spring DAO-使用JdbcTemplate进行的第一次查询花费的时间更长 [英] Spring DAO - first query with JdbcTemplate takes much longer time

查看:263
本文介绍了Spring DAO-使用JdbcTemplate进行的第一次查询花费的时间更长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用带有DAO模式的Spring MVC通过JdbcTemplate访问MSSql数据库。一切工作正常,但我注意到在每个单个请求中,第一个查询要比下一个查询花费更长的时间。

In my application I use Spring MVC with DAO pattern to access MSSql database with JdbcTemplate. Everything is working fine but I have noticed that first query takes a bit longer then next queries in each single request.

我写了一个简单的测试:

I wrote a simple test:

String sql = "SELECT 1";
for (int i = 0; i < 5; i++) {
    long startTime = System.currentTimeMillis();
    jdbcTemplate.queryForList(sql);
    logger.debug("query took: " + TimeHelper.showDuration(startTime));
}

结果是:

2012-08-28 12:55:07,665 | Start
2012-08-28 12:55:08,878 | query took: 424 milliseconds
2012-08-28 12:55:08,893 | query took: 15 milliseconds
2012-08-28 12:55:08,908 | query took: 14 milliseconds
2012-08-28 12:55:08,922 | query took: 14 milliseconds
2012-08-28 12:55:08,937 | query took: 14 milliseconds

我了解到Spring正在做一些活动来准备好所有的bean 。但是,如果有请求到服务器仅执行1个查询,则每个请求花费424毫秒。

I understand that there are some activities that Spring is doing to get all beans ready. But if there is request to server that executes only 1 query then it takes 424 miliseconds on each request.

我的问题是:这种行为可以吗?还是我的代码中可能存在一些错误?它是否起作用,以便在每个请求上Spring都需要这段时间进行初始化? (然后请求中的所有其他查询将快速运行)?或者我可以做一些启动初始化,然后在每个请求期间,第一个查询也要花费15毫秒?

My question is: Is this behavior OK? Or there can be some bug in my code? Does it work so that on each request Spring needs this time for initialization? (and all other queries in request will run fast then)? Or I can do some startup initialization and then during each request the first query will take 15 ms too?

我的配置如下:

datasource: class="org.apache.commons.dbcp.BasicDataSource"

dao被注入到测试类中:

dao is injected to test class with:

@Resource(name="testDao")  
private TestDao testDao;  

我使用基于注释的方法。测试类和DAO不使用@Transaction。

I use annotations based approach. Test class and DAO doesn't use @Transaction.

编辑:
我也尝试配置initialSize,但这并没有帮助,(initialSize = 2花费800毫秒,initialize = 1花费400毫秒-每个请求)。

I also tried to configure initialSize but this didn't help, (with initialSize=2 it takes 800ms, with initialSize=1 it takes 400ms - each request).

我不明白为什么每次请求可能要花费15毫秒的时间才能花费400毫秒。 Spring似乎有些开销。 :(

I don't understand why it takes 400ms on each request when it is possible to have it for 15 ms. It seems like some overhead with Spring. :(

推荐答案

您的数据源是一个连接池。第一个查询需要连接。后续查询将重用连接。您可以将dbcp配置为预先创建一些连接,或者在应用启动后立即手动连接并释放。

Your DataSource is a connection pool. The first query needs to connect. Subsequent queries reuse the connection. You could either configure dbcp to pre-create a few connections or connect and release manually right after the app starts.

这篇关于Spring DAO-使用JdbcTemplate进行的第一次查询花费的时间更长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆