Spring Batch 4.1.0.M1 发布

版本发布 | Mahmoud Ben Hassine | 2018 年 5 月 31 日 | ...

我们很高兴宣布 Spring Batch 4.1.0.M1 现已在 Github 和 Pivotal 下载仓库中可用。非常感谢所有为本次发布做出贡献的人!

有哪些新特性?

以下是本次发布的亮点:

  • 简化测试
  • 简化远程分块
  • 新增 JSON Item 阅读器

简化测试

Spring Batch 提供了一些有用的工具类(例如 `JobLauncherTestUtils` 和 `JobRepositoryTestUtils`)以及测试执行监听器(`StepScopeTestExecutionListener` 和 `JobScopeTestExecutionListener`)来测试批处理组件。但是,为了使用这些工具,您必须显式配置它们,如下例所示:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {JobConfiguration.class, JobTest.TestConfiguration.class})
@TestExecutionListeners(listeners = {StepScopeTestExecutionListener.class, JobScopeTestExecutionListener.class})
public class JobTest {

   @Autowired
   private JobLauncherTestUtils jobLauncherTestUtils;

   @Autowired
   private JobRepositoryTestUtils jobRepositoryTestUtils;


   @Before
   public void clearMetadata() {
      jobRepositoryTestUtils.removeJobExecutions();
   }

   @Test
   public void testJob() throws Exception {
      // given
      JobParameters jobParameters = 
            jobLauncherTestUtils.getUniqueJobParameters();

      // when
      JobExecution jobExecution = 
            jobLauncherTestUtils.launchJob(jobParameters);

      // then
      Assert.assertEquals(ExitStatus.COMPLETED, 
                          jobExecution.getExitStatus());
   }

   @Configuration
   public static class TestConfiguration {

      @Bean
      public JobLauncherTestUtils jobLauncherTestUtils() {
         return new JobLauncherTestUtils();
      }

      @Bean
      public JobRepositoryTestUtils jobRepoTestUtils(DataSource dataSource,
                                               JobRepository jobRepository) {

         return new JobRepositoryTestUtils(jobRepository, dataSource);
      }

   }
}

在此版本中,我们引入了一个名为 `@SpringBatchTest` 的新注解,它将一个类标记为 Spring Batch 组件的测试类。此注解会自动将工具 bean 和监听器添加到测试上下文,并使它们自动可用于自动注入,如下例所示:

@RunWith(SpringRunner.class)
@SpringBatchTest
@ContextConfiguration(classes = {JobConfiguration.class})
public class JobTest {

   @Autowired
   private JobLauncherTestUtils jobLauncherTestUtils;

   @Autowired
   private JobRepositoryTestUtils jobRepositoryTestUtils;


   @Before
   public void clearMetadata() {
      jobRepositoryTestUtils.removeJobExecutions();
   }

   @Test
   public void testJob() throws Exception {
      // given
      JobParameters jobParameters = 
            jobLauncherTestUtils.getUniqueJobParameters();

      // when
      JobExecution jobExecution = 
            jobLauncherTestUtils.launchJob(jobParameters);

      // then
      Assert.assertEquals(ExitStatus.COMPLETED, 
                          jobExecution.getExitStatus());
   }
   
}

通过这个新注解,您可以声明式地引入测试工具,并专注于测试批处理作业的业务逻辑。

简化远程分块

设置远程分块作业需要定义多个 bean:

  • 用于从消息中间件(JMS、AMQP 等)获取连接的连接工厂
  • 一个 `MessagingTemplate`,用于在主控端和工作端之间发送请求和响应
  • Spring Integration 的输入通道和输出通道,用于从消息中间件获取消息
  • 主控端的一个特殊 Item 写入器(`ChunkMessageChannelItemWriter`),它知道如何将数据块发送给工作端进行处理和写入
  • 工作端的一个消息监听器(`ChunkProcessorChunkHandler`),用于接收来自主控端的数据

这乍一看可能有点让人望而生畏。在此里程碑版本中,我们通过引入名为 `@EnableBatchIntegration` 的新注解以及新的 API(`RemoteChunkingMasterStepBuilder` 和 `RemoteChunkingWorkerBuilder`)来简化配置,力求使这项任务尽可能简单。示例如下:

@Configuration
@EnableBatchProcessing
@EnableBatchIntegration
public class RemoteChunkingAppConfig {
  
   @Autowired
   private RemoteChunkingMasterStepBuilderFactory masterStepBuilderFactory;
  
   @Autowired
   private RemoteChunkingWorkerBuilder workerBuilder;
  
   @Bean
   public TaskletStep masterStep() {
         return this.masterStepBuilderFactory
         	        .get("masterStep")
         	        .chunk(100)
         	        .reader(itemReader())
         	        .outputChannel(outgoingRequestsToWorkers())
         	        .inputChannel(incomingRepliesFromWorkers())
         	        .build();
   }
  
   @Bean
   public IntegrationFlow worker() {
         return this.workerBuilder
         	        .itemProcessor(itemProcessor())
         	        .itemWriter(itemWriter())
         	        .inputChannel(incomingRequestsFromMaster())
         	        .outputChannel(outgoingRepliesToMaster())
         	        .build();
   }
}

这个新注解和构建器负责配置基础设施 bean 的繁重工作。您现在可以轻松配置主控步骤以及工作端的 Spring Integration 流。

新增 JSON Item 阅读器

JSON 是当前流行的数据格式,许多应用程序需要在批处理模式下读写 JSON 数据。在第一个里程碑版本中,我们新增了一个支持 JSON 的 Item 阅读器。与用于 XML 的 `StaxEventItemReader` 类似,`JsonItemReader` 使用流式 API 来分块读取 JSON 对象。支持两种 JSON 库:JacksonGson。`JsonItemReader` 能够读取以下格式的 JSON 文件:

[
  {
    "isin": "123",
    "quantity": 1,
    "price": 1.2,
    "customer": "foo"
  },
  {
    "isin": "456",
    "quantity": 2,
    "price": 1.4,
    "customer": "bar"
  }
]

`trades.json` 文件中的每个对象都代表以下 `Trade` 类的一个实例:

public class Trade {

   private String isin;
   private long quantity;
   private BigDecimal price;
   private String customer;

   // getters and setters omitted

}

为了读取此 `trades.json` 文件,您可以使用以下 Item 阅读器(本例中使用 Jackson):

@Bean
public JsonItemReader<Trade> jsonItemReader() {

   ObjectMapper objectMapper = new ObjectMapper();
   // configure the objectMapper as required
   JacksonJsonObjectReader<Trade> jsonObjectReader = 
            new JacksonJsonObjectReader<>(Trade.class);
   jsonObjectReader.setMapper(objectMapper);

   return new JsonItemReaderBuilder<Trade>()
                 .jsonObjectReader(jsonObjectReader)
                 .resource(new ClassPathResource("trades.json"))
                 .name("tradeJsonItemReader")
                 .build();
}

其他改进

本次发布还包括许多其他改进、错误修复和文档更新。有关完整的变更列表,请查看变更日志。我们期待收到您对此里程碑版本的反馈!请随时在 Twitter 上联系 @michaelminella@benas@cppwfs,或在 StackOverflowGitter 上提问。如果您发现任何问题,请在 Jira 上提交工单。

下一步计划?

在下一个里程碑版本中,我们计划:

  • 简化远程分区设置(类似于本次里程碑版本中简化的远程分块设置)
  • 新增一个 `JsonItemWriter` 以完善 `JsonItemReader`
  • 为公共 API 添加 JSR-305 注解

敬请期待!

Spring Batch 主页 | GitHub 源码 | 参考文档

订阅 Spring 资讯

订阅 Spring 资讯,保持连接

订阅

领先一步

VMware 提供培训和认证,助您加速成长。

了解更多

获取支持

Tanzu Spring 在一个简单的订阅中提供对 OpenJDK™、Spring 和 Apache Tomcat® 的支持和二进制文件。

了解更多

近期活动

查看 Spring 社区所有近期活动。

查看全部