功能描述

在处理业务时,经常遇到需要分批次处理数据的场景,例如有105条数据,每次推送20条,分批次推送

最后不足20条数据时,一次性推送全部剩余数据

image-20231120132006402

DEMO示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package shiguang.test;

import java.util.ArrayList;
import java.util.List;

public class BatchProcessingExample {

public static void main(String[] args) {
// 模拟接口返回的数据,这里用数字代表每一条数据
List<Integer> responseData = new ArrayList<>();
for (int i = 1; i <= 105; i++) {
responseData.add(i);
}

int batchSize = 20; // 每批次处理的数据量

// 计算需要多少批次来处理所有数据
int totalDataSize = responseData.size();
int totalBatches = (int) Math.ceil((double) totalDataSize / batchSize);

// 分批次处理数据
for (int batchNumber = 0; batchNumber < totalBatches; batchNumber++) {
int startIndex = batchNumber * batchSize;
int endIndex = Math.min(startIndex + batchSize, totalDataSize);

List<Integer> batchData = responseData.subList(startIndex, endIndex);

// 在这里对批次数据进行处理,示例中只是打印数据
processBatchData(batchData);
}
}

// 处理批次数据的方法,这里只是打印数据
private static void processBatchData(List<Integer> batchData) {
for (Integer data : batchData) {
System.out.println("Processing data: " + data);
}
System.out.println("Batch processing complete.");
}
}