使用JSR223+JMeter获取响应时间



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

目标URL在采样器的"parameter"字段中给出(基于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

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

最新更新