在具有多个线程的Spring Boot Batch中进行预处理

时间:2018-06-25 12:11:56

标签: oracle spring-boot jdbc spring-batch

我有一个带有多线程的Spring批处理。在我的处理器中,我想使用全局变量(例如映射)。该映射包含一些要从表中查询并由处理器使用的值。我该如何实现?如果我编写了在处理器中设置映射的逻辑,则将对项目读取器获取的每条记录执行查询,该记录的数量为数百万。有办法吗?

1 个答案:

答案 0 :(得分:0)

您可以拦截步骤执行

Spring Batch - Reference Documentation section 5.1.10. Intercepting Step Execution

例如,您可以实现StepExecutionListener接口

@Component
@JobScope
public class Processor implements ItemProcessor<Integer,Integer>, StepExecutionListener {

    private final Map<String,String> map = new HashMap<>();

    @Override
    public void beforeStep(StepExecution stepExecution) {
        // initialize a variable once before step
        map.put("KEY","VALUE");
    }

    @Override
    public Integer process(Integer item) throws Exception {
        // use a variable for each iteration
        final String key = map.get("KEY");
        // ...
    }

    // ....
}

或使用@BeforeStep批注

@Component
@JobScope
public class Processor implements ItemProcessor<Integer,Integer>{

    private final Map<String,String> map = new HashMap<>();

    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
        // initialize a variable once before step
        map.put("KEY","VALUE");
    }

    @Override
    public Integer process(Integer item) throws Exception {
        // use a variable for each iteration
        final String key = map.get("KEY");
        //...
    }
}
相关问题