最近在做gRPC對服務端的壓測,從開發身上學習到了高級用法,記錄一下:
簡單說,就是長連接不釋放導致TCP連接數耗盡,期望通過http2解決這個問題,也就是說,其實是用gRPC來重寫了消息服務,因此需要高並發(並不是)及異步編程。
開發review了我的代碼以后,重寫成這樣了,記錄在這里學習下。
CompletableFuture<?>[] completableFutures = new CompletableFuture[num];
ExecutorService executorService = Executors.newFixedThreadPool(200);
Stopwatch mainWatch = Stopwatch.createStarted();
for (int i = 0; i < num; i++) {
completableFutures[i] = CompletableFuture.runAsync( () -> xxxxService.sendMessage("xielu_test")
, executorService);
}
CompletableFuture.allOf(completableFutures).join();
再來一版好了,雙重異步!
public ListenableFuture<ReportResponse> sendMessage(String message) {
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
try {
ListenableFuture<ReportResponse> responseFuture = messageReportStub.report(ReportRequest.newBuilder().setMessage(message).build());
return responseFuture;
} catch (final StatusRuntimeException e) {
return null;
}
}
-------------------------我是類的分割線-------------------------------------------------------------------------------------------------------
CompletableFuture completableFuture = new CompletableFuture();
ListenableFuture<ReportResponse>[] completableFutures = new ListenableFuture[num];
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(100));
Stopwatch mainWatch = Stopwatch.createStarted();
for (int i = 0; i < num; i++) {
completableFutures[i] = client.sendMessage("xielu_test");
}
Futures.addCallback(Futures.allAsList(completableFutures), new FutureCallback<List<ReportResponse>>() {
@Override
public void onSuccess(List<ReportResponse> reportResponses) {
completableFuture.complete(reportResponses);
}
@Override
public void onFailure(Throwable throwable) {
completableFuture.completeExceptionally(throwable);
}
}, executorService);
completableFuture.get();
long elapsed = mainWatch.elapsed(TimeUnit.MILLISECONDS);
String message = String.format("seed: %d, totalTime: %dms, tps: %d", num, elapsed, Math.round(num / (double) elapsed * 1000));