Last active
August 29, 2015 14:13
-
-
Save enp/0db72d34b4e671113ab3 to your computer and use it in GitHub Desktop.
HTTP clients perfomance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AsyncHttpApp { | |
ExecutorService pool = Executors.newFixedThreadPool(25); | |
private interface Provider { | |
public void provide(String url, int times) throws Exception; | |
} | |
private class PlainProvider implements Provider { | |
public void provide(final String url, int times) throws Exception { | |
List<Future<Integer>> futures = new ArrayList<Future<Integer>>(); | |
for (int i = 0; i < times; i++) { | |
futures.add(pool.submit(new Callable<Integer>() { | |
public Integer call() throws Exception { | |
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); | |
int result = IOUtils.toString(connection.getInputStream()).length(); | |
connection.disconnect(); | |
return result; | |
} | |
})); | |
} | |
for (Future<Integer> future : futures) | |
System.out.println(future.get()+":"+System.currentTimeMillis()/1000+" "); | |
} | |
public String toString() { | |
return "PlainProvider"; | |
} | |
} | |
private class AsyncProvider implements Provider { | |
AsyncHttpClient client; | |
public AsyncProvider(AsyncHttpProvider provider) { | |
this.client = new AsyncHttpClient(provider); | |
} | |
public void provide(String url, int times) throws Exception { | |
try { | |
List<Future<Response>> futures = new ArrayList<Future<Response>>(); | |
for (int i = 0; i < times; i++) { | |
futures.add(client.prepareGet(url).execute()); | |
} | |
for (Future<Response> future : futures) | |
System.out.println(future.get().getResponseBody().length()+":"+System.currentTimeMillis()/1000+" "); | |
} finally { | |
client.close(); | |
} | |
} | |
public String toString() { | |
return client.getProvider().getClass().getSimpleName(); | |
} | |
} | |
public AsyncHttpApp() { | |
AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder().setExecutorService(pool).build(); | |
Provider[] providers = new Provider[] { | |
new PlainProvider(), | |
new AsyncProvider(new JDKAsyncHttpProvider(config)), | |
new AsyncProvider(new NettyAsyncHttpProvider(config)) | |
}; | |
for (Provider provider : providers) { | |
long begin = System.currentTimeMillis(); | |
try { | |
provider.provide("http://10.7.1.13:3000", 20); | |
} catch (Exception e) { | |
System.err.println(e.getMessage()); | |
} | |
long total = System.currentTimeMillis() - begin; | |
System.out.println(provider + " : " + total); | |
} | |
pool.shutdown(); | |
} | |
public static void main(String[] args) { | |
new AsyncHttpApp(); | |
} | |
} |
slandelle
commented
Jan 13, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment