【发布时间】:2016-05-25 16:36:09
【问题描述】:
我想从数据库中写入 json 格式的文件。
我有这个ItemWriter实现的原型,很简单。
import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ItemWriter;
import org.springframework.core.io.Resource;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class CustomItemWriter<T> implements ItemWriter<T>, StepExecutionListener {
private Gson gson;
private Resource resource;
private boolean shouldDeleteIfExists = true;
private List<T> allItems = new ArrayList<T>();
@Override
public void write(List<? extends T> items) throws Exception {
System.out.println("this is the begin " + items.size());
allItems.addAll(items);
}
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public boolean isShouldDeleteIfExists() {
return shouldDeleteIfExists;
}
public void setShouldDeleteIfExists(boolean shouldDeleteIfExists) {
this.shouldDeleteIfExists = shouldDeleteIfExists;
}
@Override
public ExitStatus afterStep(StepExecution arg0) {
//write ALL to the output file
System.out.println(gson.toJson(allItems));
return null;
}
@Override
public void beforeStep(StepExecution arg0) {
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").disableHtmlEscaping().create();
}
}
这里解决的问题是,write 方法向输出文件中的每个commitInterval 发送一个 JSON 数组,我只想在我的文件中有一个唯一的 JSON 数组。
在步骤运行后实现StepExecutionListener;我可以将整个数组发送到输出文件并将其转换为 JSON,然后将其写入输出文件(很好!)。
我的问题是,这是正确的方法吗?我认为每个commitInterval 都写入文件有好处,但我不确定我的解决方案。它有效,但我不想解决这个问题并激怒另一个问题。
【问题讨论】:
标签: java json spring-batch