【发布时间】:2020-03-11 21:42:01
【问题描述】:
在 Spring Batch 中,处理器从一种输入类型映射到一种输出类型。但是我需要从一个I 生成一个输出类型列表(List<O>)。
处理器可以很好地返回List<O>,但假设我想在后续处理器中作为个体使用此列表中的元素。我应该先将它们写入数据库吗?事实上,我从远程服务中得到了一些丰富,需要对List<O> 的每个成员进行处理,所以我不希望将它们写在任何地方,直到可以处理列表中的各个对象。
这与我的previous post 有关,我在其中被告知@JobScope 和步骤之间对象的内存传输90% 是代码异味。我很好奇我是否在这里错过了一个特殊的 Spring Batch 模式,用于展平列表的结果列表,这与在处理之前将半生不熟的对象写入数据库、缓存或平面文件不同。
但最终我希望作者使用O 的一部分,而不是List<O> 的一部分。那么推荐的方法是什么?到目前为止,我想出了以下用作@JobScope bean:
public class FlatMapPipe<T> implements ItemWriter<List<T>>, ItemReader<T> {
private LinkedList<List<T>> lists = new LinkedList<List<T>>();
/**
* Pages through the internal linked list to find the next item
* @return next item in the current list or the first item in the next list or null
* @throws Exception
* @throws UnexpectedInputException
* @throws ParseException
* @throws NonTransientResourceException
*/
@Override
public T read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
if (lists.size() == 0) {
return null;
}
List<T> list = lists.get(0);
if (list.isEmpty()) {
lists.remove();
return read();
} else {
return list.remove(0);
}
}
/**
* Appends a list to the linked list of lists of written Items
* @param list
* @throws Exception
*/
@Override
public void write(List<? extends List<T>> list) throws Exception {
list.forEach((it) -> lists.add(new ArrayList<>(it)));
}
}
【问题讨论】:
标签: spring-batch