大数据分批执行方法
欢迎使用Markdown编辑器
在游戏额数据比较大清空下,可能需要分批执行方法(比如数据库操作),记录一些通用分批处理方法
无返回值方法
public static <T> void batchOperate(List<T> list, Consumer<List<T>> consumer, int pageSize) {
long start = System.currentTimeMillis();
int endIndex;
for (int i = 0; i <list.size() ; i += pageSize) {
endIndex = Math.min(i+pageSize,list.size());
if(i >= endIndex){
break;
}
List<T> ts = list.subList(i, endIndex);
consumer.accept(ts);
}
log.debug("批量执行耗时【{}】ms",System.currentTimeMillis() - start);
}
有返回值方法
public static <T,R> List<R> batchOperate(List<T> list, Function<List<T>,List<R>> func, int pageSize) {
long start = System.currentTimeMillis();
List<R> result = new ArrayList<>(list.size());
int endIndex;
for (int i = 0; i <list.size() ; i += pageSize) {
endIndex = Math.min(i+pageSize,list.size());
if(i >= endIndex){
break;
}
List<T> ts = list.subList(i, endIndex);
result.addAll(func.apply(ts));
}
log.debug("批量执行耗时【{}】ms",System.currentTimeMillis() - start);
return result;
}
本文介绍了在大数据场景下,如何使用Java进行分批处理的两种方法:无返回值和有返回值的方法。无返回值方法适用于执行清理任务,而有返回值方法则适用于需要收集处理结果的情况。通过这两个方法,可以有效地处理大量数据,避免一次性加载所有数据导致的性能问题。同时,代码中还记录了批量执行的耗时,方便性能分析。
8614

被折叠的 条评论
为什么被折叠?



