如何在Spring Batch中按顺序划分一系列步骤

时间:2018-10-11 01:11:45

标签: spring-batch partition

我知道Spring Batch框架可以划分一个主步骤,以便并行运行多个从步骤。

我的要求是按顺序划分一系列连续步骤(例如流)以操作多个表,而不是仅一步操作。我只能想到两种选择。

  1. 仅创建一个小任务,以汇编所有逻辑以更新序列表。
  2. 为流程中的每个步骤创建分区步骤。

理想情况下,我希望Spring Batch支持开箱即用的功能。请阐明实现目标的最佳方法是什么。

一个例子深表感谢。

更新:我做了一些Google搜索,发现我可以使用FlowStep对流进行如下划分。这是正确的方法吗?

<?php
class PDOMysqlAdapter {
  public $db;
  public $result;
  public $test = array(1,2);

  public function get(){
    return $this->test;
  }

  public function __construct($host, $port, $dbname, $username, $password, $charset = "utf8") {
    $this->db = new PDO(
      "mysql:host={$host};port={$port};dbname={$dbname};charset={$charset}",
      $username,
      $password
    );
    $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }

  public function singleton($sql, $debug = false) {
    if($debug) { error_log("Executing:\n\n{$sql}\n"); }

    try {
      $this->result = $this->db->query($sql)->fetch(PDO::FETCH_ASSOC);
      if($debug) { error_log(print_r($this->result, true)); }
      return $this->result;
    } catch(PDOException $ex) {
      error_log($ex->getMessage()."\n");
      return NULL;
    }
  }

  public function multiple($sql, $debug = false) {
    if($debug) { error_log("Executing:\n\n{$sql}\n"); }

    try {
      $this->result = $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
      if($debug) { error_log(print_r($this->result, true)); }
      error_log(count($this->result));
      return $this->result;
    } catch(PDOException $ex) {
      error_log($ex->getMessage()."\n");
      return NULL;
    }
  }
}

$db = new PDOMysqlAdapter(DB_SERVER, DB_PORT, DB_NAME, DB_USER, DB_PASS);

error_log(print_r($db->get(), true)); // does what I think it should

$result = $db->singleton("SELECT 1", true);
error_log(print_r($result, true));  // return { '1' => '1' }

$foo = $db->multiple("SELECT * FROM users LIMIT 2", true); // query returns without error and result exists within scope
error_log(print_r($foo, true));  // null
error_log(count($db->result));   // variable is public and full of expected contents

1 个答案:

答案 0 :(得分:0)

您可以按顺序定义一个包含多个步骤的作业,每个步骤都是一个分区的步骤:

public Job job() {
    return jobBuilderFactory("job")
            .start(step1()) // step1 is a partitioned step
            .next(step2()) // step2 is also a partitioned step
            .build();
}

您可以在我的答案中找到一个带有示例的类似问题:Is it possible to combine partition and parallel steps in spring batch?

希望这会有所帮助。