|
如果没有 AsyncResponse,性能与 ExecutorService 相同。如果多个 API 调用必须异步并且链接起来,那么这种方法更好(类似 Node 中的 Promises)。
- ExecutorService ioExecutorService = CustomThreads.getExecutorService(ioPoolSize);
-
- // I/O 任务
- CompletableFuture<String> postsFuture = CompletableFuture.supplyAsync(JsonService::getPosts, ioExecutorService);
- CompletableFuture<String> commentsFuture = CompletableFuture.supplyAsync(JsonService::getComments,
- ioExecutorService);
- CompletableFuture<String> albumsFuture = CompletableFuture.supplyAsync(JsonService::getAlbums,
- ioExecutorService);
- CompletableFuture<String> photosFuture = CompletableFuture.supplyAsync(JsonService::getPhotos,
- ioExecutorService);
- CompletableFuture.allOf(postsFuture, commentsFuture, albumsFuture, photosFuture).get();
-
- // 从 I/O 任务(阻塞调用)获得响应
- String posts = postsFuture.get();
- String comments = commentsFuture.get();
- String albums = albumsFuture.get();
- String photos = photosFuture.get();
-
- // 合并响应(内存中的任务将是此操作的一部分)
- String postsAndCommentsOfRandomUser = ResponseUtil.getPostsAndCommentsOfRandomUser(userId, posts, comments);
- String albumsAndPhotosOfRandomUser = ResponseUtil.getAlbumsAndPhotosOfRandomUser(userId, albums, photos);
-
- // 构建最终响应并将其发送回客户端
- return postsAndCommentsOfRandomUser + albumsAndPhotosOfRandomUser;
7. 使用 ExecutorService 并行处理所有任务
(编辑:PHP编程网 - 湛江站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|