使用JSR223 + JMeter获取响应时间

时间:2016-08-03 20:12:17

标签: api groovy jmeter jsr223

是否有可能获得在JMeter中使用JSR223 / groovy采样器进行的API请求的实际响应时间?我有以下工作代码,但在观看我的听众时没有得到适当的响应时间(响应内容实际上很好,有些json数据)。

目标网址在'参数'中提供。采样器中的字段(基于Dmitri的例子)。此外,我在标头中添加了一个承载令牌,以便在执行请求时使用OAuth访问令牌。

我确实尝试使用事务控制器并在其中包含JSR223采样器,但这不能用于获取响应时间(即使在创建父样本时也不行)。

import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.util.EntityUtils

import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

List<String> urls = new ArrayList<String>(); // initialize array of URLs
Collections.addAll(urls, args); // read URLs from "Parameters" input and add them to array
ExecutorService pool = Executors.newFixedThreadPool(urls.size());

// initialize pool of Future Tasks with number of threads equal to size of URLs provided
for (String url : urls) { // for each URL from list
    final String currentURL = url;
    pool.submit(new Runnable() { // Sumbit a new thread which will execute GET request

        @Override
        public void run() {
            try {
                HttpClient client = new DefaultHttpClient();                // Use Apache Commons HTTPClient to perform GET request
                HttpGet get = new HttpGet(currentURL);                      

                get.addHeader("authorization","Bearer ${AccessToken}");     // Add the access token into the header 
                get.addHeader("connection","keep-alive");                   // Add keep-alive in header

                HttpResponse response = client.execute(get);                // HttpResponse response = client.execute(post);
                HttpEntity entity = response.getEntity();
                log.info("Response Status Code: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());       
                SampleResult.setResponseData(EntityUtils.toByteArray(entity));        
            } catch (Exception ex) {
                ex.printStackTrace();
                throw ex;
            }

        }
    });
}
pool.shutdown(); // shut down thread pool

1 个答案:

答案 0 :(得分:3)

您的示例在执行请求的线程完成之前返回, ThreadPoolExecutor的shutdown()方法启动关闭但不等待它。 尝试使用awaitTermination:pool.awaitTermination(60, TimeUnit.SECONDS)