DMC DMC - 1 year ago 143
Groovy Question

getting response times using JSR223 + JMeter

Is it possible to get the actual response time of API requests made using the JSR223/groovy sampler in JMeter ? I have the following working code, but do not get proper response time when i watch my listeners (response content is actually fine, some json data).

The target URL is given in the 'parameter' field in the sampler (based on Dmitri's example). Furthermore i added a bearer token into header to use the OAuth access token when doing requests.

I did try to use a Transaction controller and include the JSR223 sampler within it, but this did not work in getting the response time (even not when creating a parent sample).

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

Answer Source

Your sample returns before the thread executing your request is finished, the shutdown() method of ThreadPoolExecutor initiates the shutdown but does not wait for it . Try with awaitTermination: pool.awaitTermination(60, TimeUnit.SECONDS)