2016-08-03 81 views
2

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

目标URL在采样器的'参数'字段中给出(基于德米特里的例子)。此外,我在请求中添加了一个不记名标记,以便使用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

你的问题不清楚。你的意思是你希望得到'HttpResponse response = client.execute(get);'的响应时间而不是整个采样器的响应时间?或者是其他东西? –

+0

是样本的响应时间。我确实得到了一个有效的响应内容(json消息)。但我想知道请求花了多长时间,因此我需要知道响应时间。 对于我现在看到的,jsr223采样器的响应时间大约是10-20ms左右,这是不正确的(对于此api请求应该在1秒以上)。 – DMC

+0

奇怪:我认为采样器会比单个操作更长。它可能与使用单独的线程来运行代码有关。基本上JMeter所做的主要假设是每个采样器都是由单个线程执行的单个“操作”。而且你有多个线程并行处理多个URL到多个URL。所以它可能会变得怪异。我建议让采样器处理一件事,并控制线程组级 –

回答

3

你的样品返回结束后, 的ThreadPoolExecutor的shutdown()方法启动关闭,但不等待它。 尝试用await Termination:pool.awaitTermination(60, TimeUnit.SECONDS)

+0

我的代码如何看起来像?如果我替换pool.shutdown(); 'pool.awaitTermination(60,TimeUnit.SECONDS)'然后我得到一个响应消息:javax.script.ScriptException:groovy.lang.MissingPropertyException:没有这样的属性:TimeUnit类:Script4 – DMC

+0

固定与导入java.util。 concurrent.TimeUnit,但是示例现在似乎永远运行直到达到超时。然后显示响应。响应/加载时间也是60秒 – DMC

+1

公顷对不起,我忘记了导入。你必须做关机然后等待。我不是很清楚,我的不好。 – ARA