zoukankan      html  css  js  c++  java
  • 线程池,CompletableFuture学习

       最近在做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));
  • 相关阅读:
    权限管理
    书城项目第五阶段---book表的curd
    大话设计模式学习
    数据绑定流程分析
    GO 解决使用bee工具,报 bash: bee: command not found
    VScode插件:Todo Tree
    ant design pro如何实现分步表单时,返回上一步值依然被保存
    React开发流程
    为什么函数式组件没有生命周期?
    html2canvas@^1.0.0-rc.1
  • 原文地址:https://www.cnblogs.com/spillage/p/11422971.html
Copyright © 2011-2022 走看看