当前位置:主页 > 查看内容

Java 数据分批调用接口的正确姿势

发布时间:2021-08-18 00:00| 位朋友查看

简介:// 如果仅调用doReturn一次,那么每次返回都是key相同的Map, // 如果需要不覆盖,则doReturn次数和 invocations 相同) int eachReturnSize = 3; PowerMockito .doReturn(mockMap(eachReturnSize)) .doReturn(mockMap(eachReturnSize)) .when(someManager).……
// 如果仅调用doReturn一次,那么每次返回都是key相同的Map, // 如果需要不覆盖,则doReturn次数和 invocations 相同) int eachReturnSize = 3; PowerMockito .doReturn(mockMap(eachReturnSize)) .doReturn(mockMap(eachReturnSize)) .when(someManager).aMapMethod(anyLong(), any()); // 每批 int size = 16; Map String, Integer resultMap = ExecuteUtil.partitionCall2Map(mockDataList, size, (eachList) - someManager.aMapMethod(2L, eachList)); //验证执行次数 int invocations = 2; Mockito.verify(someManager, new Times(invocations)).aMapMethod(anyLong(), any()); // 正好几轮 int turns; if (total % size == 0) { turns = total / size; } else { turns = total / size + 1; Assert.assertEquals(turns * eachReturnSize, resultMap.size()); private Map String, Integer mockMap(int size) { Map String, Integer result = new HashMap (size); for (int i = 0; i size; i++) {

// 极力保证key不重复

 result.put(easyRandom.nextObject(String.class) + RandomUtils.nextInt(), easyRandom.nextInt());
 return result;

}
注意:

1 判空

.filter(Objects::nonNull)
这里非常重要,避免又一次调用返回 null,而导致空指针异常。

2 实际使用时可以结合apollo配置, 灵活设置每批执行的数量,如果超时随时调整

3 用到的类库

集合工具类: commons-collections4、guava (可以不用)

这里的list划分子list也可以使用stream的 skip ,limit特性自己去做,集合判空也可以不借助collectionutils.

构造数据:easy-random

单元测试框架: Junit4 、 powermockito、mockito

4 大家可以加一些更强大的功能,如允许设置每次调用的时间间隔、并行或并发调用等。

三、改进
以上面的List接口为例,将其改为异步版本:

public static T, V List V partitionCall2ListAsync(List T dataList,
 int size,
 ExecutorService executorService,
 Function List T , List V function) {
 if (CollectionUtils.isEmpty(dataList)) {
 return new ArrayList (0);
 Preconditions.checkArgument(size 0, "size must not be a minus");
 List CompletableFuture List V completableFutures = Lists.partition(dataList, size)
 .stream()
 .map(eachList - {
 if (executorService == null) {
 return CompletableFuture.supplyAsync(() - function.apply(eachList));
 } else {
 return CompletableFuture.supplyAsync(() - function.apply(eachList), executorService);
 .collect(Collectors.toList());

本文转自网络,原文链接:https://developer.aliyun.com/article/787278
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:EasyExcel教程 下一篇:没有了

推荐图文

  • 周排行
  • 月排行
  • 总排行

随机推荐