Random random = new Random(System.nanoTime());
String contextPath = "/lightLoad";
String servletMapping = "/server";
int port1 = random.nextInt(50000) + 10000;
Server server1 = new Server(port1);
WebAppContext context1 = new WebAppContext(warDir.getCanonicalPath(), contextPath);
context1.setSessionHandler(new SessionHandler());
context1.addServlet(TestServlet.class, servletMapping);
server1.setHandler(context1);
server1.start();
try
{
int port2 = random.nextInt(50000) + 10000;
Server server2 = new Server(port2);
WebAppContext context2 = new WebAppContext(warDir.getCanonicalPath(), contextPath);
context2.setSessionHandler(new SessionHandler());
context2.addServlet(TestServlet.class, servletMapping);
server2.setHandler(context2);
server2.start();
try
{
HttpClient client = new HttpClient();
client.setConnectorType(HttpClient.CONNECTOR_SOCKET);
client.start();
try
{
String[] urls = new String[2];
urls[0] = "http://localhost:" + port1 + contextPath + servletMapping;
urls[1] = "http://localhost:" + port2 + contextPath + servletMapping;
ContentExchange exchange1 = new ContentExchange(true);
exchange1.setMethod(HttpMethods.GET);
exchange1.setURL(urls[0] + "?action=init");
client.send(exchange1);
exchange1.waitForDone();
assert exchange1.getResponseStatus() == HttpServletResponse.SC_OK;
String sessionCookie = exchange1.getResponseFields().getStringField("Set-Cookie");
assert sessionCookie != null;
System.out.println("sessionCookie = " + sessionCookie);
ExecutorService executor = Executors.newCachedThreadPool();
int clientsCount = 50;
CyclicBarrier barrier = new CyclicBarrier(clientsCount + 1);
int requestsCount = 100;
Worker[] workers = new Worker[clientsCount];
for (int i = 0; i < clientsCount; ++i)
{
workers[i] = new Worker(barrier, requestsCount, sessionCookie, urls);
workers[i].start();
executor.execute(workers[i]);
}
// Wait for all workers to be ready
barrier.await();
long start = System.nanoTime();
// Wait for all workers to be done
barrier.await();
long end = System.nanoTime();
long elapsed = TimeUnit.NANOSECONDS.toMillis(end - start);
System.out.println("elapsed ms: " + elapsed);
for (Worker worker : workers) worker.stop();
executor.shutdownNow();
// Perform one request to get the result
ContentExchange exchange2 = new ContentExchange(true);
exchange2.setMethod(HttpMethods.GET);
exchange2.setURL(urls[0] + "?action=result");
exchange2.getRequestFields().add("Cookie", sessionCookie);
client.send(exchange2);
exchange2.waitForDone();
assert exchange2.getResponseStatus() == HttpServletResponse.SC_OK;
String response = exchange2.getResponseContent();
System.out.println("get = " + response);
assert response.trim().equals(String.valueOf(clientsCount * requestsCount));
}
finally
{
client.stop();
}
}
finally
{
server2.stop();
}
}
finally
{
server1.stop();