Spring Boot 高效数据聚合之道

项目地址和示例代码: https://github.com/lvyahui8/spring-boot-data-aggregator

背景

接口开发是后端开发中最常见的场景, 可能是RESTFul接口, 也可能是RPC接口. 接口开发往往是从各处捞出数据, 然后组装成结果, 特别是那些偏业务的接口.

例如, 我现在需要实现一个接口, 拉取用户基础信息+用户的博客列表+用户的粉丝数据的整合数据, 假设已经有如下三个接口可以使用, 分别用来获取 用户基础信息 ,用户博客列表, 用户的粉丝数据.

用户基础信息

@Service public class UserServiceImpl implements UserService { @Override public User get(Long id) { try {Thread.sleep(1000L);} catch (InterruptedException e) {} /* mock a user*/ User user = new User(); user.setId(id); user.setEmail("lvyahui8@gmail.com"); user.setUsername("lvyahui8"); return user; } }

用户博客列表

@Service public class PostServiceImpl implements PostService { @Override public List<Post> getPosts(Long userId) { try { Thread.sleep(1000L); } catch (InterruptedException e) {} Post post = new Post(); post.setTitle("spring data aggregate example"); post.setContent("No active profile set, falling back to default profiles"); return Collections.singletonList(post); } }

用户的粉丝数据

@Service public class FollowServiceImpl implements FollowService { @Override public List<User> getFollowers(Long userId) { try { Thread.sleep(1000L); } catch (InterruptedException e) {} int size = 10; List<User> users = new ArrayList<>(size); for(int i = 0 ; i < size; i++) { User user = new User(); user.setUsername("name"+i); user.setEmail("email"+i+"@fox.com"); user.setId((long) i); users.add(user); }; return users; } }

注意, 每一个方法都sleep了1s以模拟业务耗时.

我们需要再封装一个接口, 来拼装以上三个接口的数据.

PS: 这样的场景实际在工作中很常见, 而且往往我们需要拼凑的数据, 是要走网络请求调到第三方去的. 另外可能有人会想, 为何不分成3个请求? 实际为了客户端网络性能考虑, 往往会在一次网络请求中, 尽可能多的传输数据, 当然前提是这个数据不能太大, 否则传输的耗时会影响渲染. 许多APP的首页, 看着复杂, 实际也只有一个接口, 一次性拉下所有数据, 客户端开发也简单.

串行实现

编写性能优良的接口不仅是每一位后端程序员的技术追求, 也是业务的基本诉求. 一般情况下, 为了保证更好的性能, 往往需要编写更复杂的代码实现.

但凡人皆有惰性, 因此, 往往我们会像下面这样编写串行调用的代码

@Component public class UserQueryFacade { @Autowired private FollowService followService; @Autowired private PostService postService; @Autowired private UserService userService; public User getUserData(Long userId) { User user = userService.get(userId); user.setPosts(postService.getPosts(userId)); user.setFollowers(followService.getFollowers(userId)); return user; } }

很明显, 上面的代码, 效率低下, 起码要3s才能拿到结果, 且一旦用到某个接口的数据, 便需要注入相应的service, 复用麻烦.

并行实现

有追求的程序员可能立马会考虑到, 这几项数据之间并无强依赖性, 完全可以并行获取嘛, 通过异步线程+CountDownLatch+Future实现, 就像下面这样.

@Component public class UserQueryFacade { @Autowired private FollowService followService; @Autowired private PostService postService; @Autowired private UserService userService; public User getUserDataByParallel(Long userId) throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newFixedThreadPool(3); CountDownLatch countDownLatch = new CountDownLatch(3); Future<User> userFuture = executorService.submit(() -> { try{ return userService.get(userId); }finally { countDownLatch.countDown(); } }); Future<List<Post>> postsFuture = executorService.submit(() -> { try{ return postService.getPosts(userId); }finally { countDownLatch.countDown(); } }); Future<List<User>> followersFuture = executorService.submit(() -> { try{ return followService.getFollowers(userId); }finally { countDownLatch.countDown(); } }); countDownLatch.await(); User user = userFuture.get(); user.setFollowers(followersFuture.get()); user.setPosts(postsFuture.get()); return user; } }

上面的代码, 将串行调用改为并行调用, 在有限并发级别下, 能极大提高性能. 但很明显, 它过于复杂, 如果每个接口都为了并行执行都写这样一段代码, 简直是噩梦.

优雅的注解实现

熟悉java的都知道, java有一种非常便利的特性 ~~ 注解. 简直是黑魔法. 往往只需要给类或者方法上添加一些注解, 便可以实现非常复杂的功能.

有了注解, 再结合Spring依赖自动注入的思想, 那么我们可不可以通过注解的方式, 自动注入依赖, 自动并行调用接口呢? 答案是肯定的.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpfypf.html