加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 湛江站长网 (https://www.0759zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

鸟瞰 Java 并发框架

发布时间:2019-07-18 22:44:23 所属栏目:建站 来源:唐尤华
导读:副标题#e# 1. 为什么要写这篇文章 几年前 NoSQL 开始流行的时候,像其他团队一样,我们的团队也热衷于令人兴奋的新东西,并且计划替换一个应用程序的数据库。但是,当深入实现细节时,我们想起了一位智者曾经说过的话:细节决定成败。最终我们意识到 NoSQL

如果没有 AsyncResponse,性能与 ExecutorService 相同。如果多个 API 调用必须异步并且链接起来,那么这种方法更好(类似 Node 中的 Promises)。

  1. ExecutorService ioExecutorService = CustomThreads.getExecutorService(ioPoolSize); 
  2.  
  3. // I/O 任务 
  4. CompletableFuture<String> postsFuture = CompletableFuture.supplyAsync(JsonService::getPosts, ioExecutorService); 
  5. CompletableFuture<String> commentsFuture = CompletableFuture.supplyAsync(JsonService::getComments, 
  6.     ioExecutorService); 
  7. CompletableFuture<String> albumsFuture = CompletableFuture.supplyAsync(JsonService::getAlbums, 
  8.     ioExecutorService); 
  9. CompletableFuture<String> photosFuture = CompletableFuture.supplyAsync(JsonService::getPhotos, 
  10.     ioExecutorService); 
  11. CompletableFuture.allOf(postsFuture, commentsFuture, albumsFuture, photosFuture).get(); 
  12.  
  13. // 从 I/O 任务(阻塞调用)获得响应 
  14. String posts = postsFuture.get(); 
  15. String comments = commentsFuture.get(); 
  16. String albums = albumsFuture.get(); 
  17. String photos = photosFuture.get(); 
  18.  
  19. // 合并响应(内存中的任务将是此操作的一部分) 
  20. String postsAndCommentsOfRandomUser = ResponseUtil.getPostsAndCommentsOfRandomUser(userId, posts, comments); 
  21. String albumsAndPhotosOfRandomUser = ResponseUtil.getAlbumsAndPhotosOfRandomUser(userId, albums, photos); 
  22.  
  23. // 构建最终响应并将其发送回客户端 
  24. return postsAndCommentsOfRandomUser + albumsAndPhotosOfRandomUser; 

7. 使用 ExecutorService 并行处理所有任务

(编辑:PHP编程网 - 湛江站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!