2

我必须做一批:
从数据库中读取一些数据(每一行都是一个项目,这很好)
然后做一些过程来添加更多数据(更多数据总是更好;))
然后这是我的问题,我有将每个项目写入 xml 文件,其名称取决于项目的数据。

例如我有
ItemA (attr1=toto, attr2=foo, attr3=myNonKeyData...)=>进入 toto_foo.xml
ItemB (attr1=toto, attr2=foo, attr3=myNonKeyData...)=>进入 toto_foo .xml

ItemC (attr1=tata, attr2=foo...)=>进入 tata_foo.xml
...

我看不到如何只运行一次批处理。
我有太多的键和可能的输出文件来做分类器。
也许使用分区器可能是一个好主意,即使它似乎不是为此而设计的。

4

1 回答 1

5

这是我所理解的。

  • 任意数量的文件。
  • 一次处理来自 DB 的数据 - 从 DB 读取一次并写入多个文件。
  • 正在写入的项目的一个或多个属性确定要写入的目标文件的名称。

创建一个复合 ItemWriter(灵感来自 org.springframework.batch.item.support.CompositeItemWriter)。这是一些伪代码

public class MyCompositeItemWriter<T> implements ItemStreamWriter<T> {

// The String key is the file-name(toto_foo.xml, tata_foo.xml etc)
//The map will be empty to start with as we do not know how many files will be created. 
private Map<String, ItemWriter<? super T>> delegates;

private boolean ignoreItemStream = false;

public void setIgnoreItemStream(boolean ignoreItemStream) {
    this.ignoreItemStream = ignoreItemStream;
}

@Override
public void write(List<? extends T> items) throws Exception {

    for(T item : items) {
        ItemWriter<? super T> writer = getItemWriterForItem(item);
        // Writing one item ata time might be inefficent. You can optimize this by grouping items by fileName. 
        writer.write(item);     
    }       
}


private getItemWriterForItem(T item) {
    String fileName = getFileNameForItem(item); 
    ItemWriter<? super T> writer = delegates.get(fileName);
    if(writer == null) {
        // There is no writer for the fileName. 
        //create one
        writer = createMyItemWriter(fileName);
        delegates.put(fileName, writer);
    }
    return writer;
}

ItemWriter<? super T> createMyItemWriter(String fileName) {
    // create the writer. Maybe a org.springframework.batch.item.xml.StaxEventItemWriter 
    // set the resource(fielName)
    //open the writer
}




// Identify the name of the target file - toto_foo.xml, tata_foo.xml etc
private String getFileNameForItem(Item item) {
    .....
}

@Override
public void close() throws ItemStreamException {
    for (ItemWriter<? super T> writer : delegates) {
        if (!ignoreItemStream && (writer instanceof ItemStream)) {
            ((ItemStream) writer).close();
        }
    }
}

@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
    // Do nothing as we do not have any writers to begin with. 
    // Writers will be created as needed. And will be opened after creation. 
}

@Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
    for (ItemWriter<? super T> writer : delegates) {
        if (!ignoreItemStream && (writer instanceof ItemStream)) {
            ((ItemStream) writer).update(executionContext);
        }
    }
}
于 2015-01-19T21:40:47.337 回答