并行执行工作流步骤

并行步骤可减少工作流的总执行时间,具体做法如下: 执行多次阻塞调用

阻塞调用,例如 sleepHTTP 调用以及 回调可能需要一定的时间 从几毫秒到几天。并行步骤旨在协助执行此类并发操作 长时间运行的操作如果工作流必须执行多次阻塞调用 彼此独立,使用并行分支可以减少 同时发起调用,并等待所有 完成这些任务

例如,如果您的工作流程必须从多个数据源 独立的系统之后再继续,并行分支允许并发 API 请求。如果有五个系统,每个系统需要 2 秒作出响应, 在工作流中依序执行这些步骤可能需要至少 10 秒钟的时间; 同时执行这些任务只需两个时间。

创建并行步骤

创建一个 parallel 步骤来定义工作流的两个或更多步骤 可以同时执行多个步骤。

YAML

  - PARALLEL_STEP_NAME:
      parallel:
        exception_policy: POLICY
        shared: [VARIABLE_A, VARIABLE_B, ...]
        concurrency_limit: CONCURRENCY_LIMIT
        BRANCHES_OR_FOR:
          ...

JSON

  [
    {
      "PARALLEL_STEP_NAME": {
        "parallel": {
          "exception_policy": "POLICY",
          "shared": [
            "VARIABLE_A",
            "VARIABLE_B",
            ...
          ],
          "concurrency_limit": "CONCURRENCY_LIMIT",
          "BRANCHES_OR_FOR":
          ...
        }
      }
    }
  ]

替换以下内容:

  • PARALLEL_STEP_NAME:并行步骤的名称。
  • POLICY(可选):确定其他操作 分支将发生未处理的异常。默认政策 continueAll,不会产生进一步的操作,所有其他分支都会 错误。请注意,continueAll 是目前唯一支持的政策。
  • VARIABLE_AVARIABLE_B 等 on:父作用域允许赋值的可写变量列表 并行执行的步骤。如需了解详情,请参阅 共享变量
  • CONCURRENCY_LIMIT(可选): 可在单个工作流中同时执行的分支和迭代 之后,其他分支和迭代就会排队等待。这个 仅适用于单个 parallel 步骤,不级联。必须为 正整数,可以是字面量值或表达式。对于 请参阅 并发限制
  • BRANCHES_OR_FOR:使用 branchesfor 表示以下其中一项:
    • 可以同时运行的分支。
    • 迭代可以并发运行的循环。

请注意以下几点:

  • 并行分支和迭代可以按任何顺序运行, 每次执行的顺序都不同。
  • 并行步骤可包含其他嵌套的并行步骤,但不得超过深度。 请参阅配额和限制
  • 有关详情,请参阅 并行步骤
。 <ph type="x-smartling-placeholder">

用并行步骤替换实验函数

如果您使用 experimental.executions.map 支持并行工作,则可以 将工作流改为采用并行步骤, 并行执行 for 循环。如需查看示例,请参阅 将实验函数替换为并行步骤

示例

这些示例演示了语法。

并行执行操作(使用分支)

如果您的工作流包含多组不同的步骤 同时,将它们放在并行分支中可以减少总时间 完成这些步骤所需的资源。

在以下示例中,用户 ID 作为参数传递给工作流,并且 数据是通过两个不同的服务并行检索的。 共享变量 允许在分支中写入值,并在分支之后读取值 完成:

YAML

main:
  params: [input]
  steps:
    - init:
        assign:
          - userProfile: {}
          - recentItems: []
    - enrichUserData:
        parallel:
          shared: [userProfile, recentItems]  # userProfile and recentItems are shared to make them writable in the branches
          branches:
            - getUserProfileBranch:
                steps:
                  - getUserProfile:
                      call: http.get
                      args:
                        url: '${"https://example.com/users/" + input.userId}'
                      result: userProfile
            - getRecentItemsBranch:
                steps:
                  - getRecentItems:
                      try:
                        call: http.get
                        args:
                          url: '${"https://example.com/items?userId=" + input.userId}'
                        result: recentItems
                      except:
                        as: e
                        steps:
                          - ignoreError:
                              assign:  # continue with an empty list if this call fails
                                - recentItems: []

JSON

{
  "main": {
    "params": [
      "input"
    ],
    "steps": [
      {
        "init": {
          "assign": [
            {
              "userProfile": {}
            },
            {
              "recentItems": []
            }
          ]
        }
      },
      {
        "enrichUserData": {
          "parallel": {
            "shared": [
              "userProfile",
              "recentItems"
            ],
            "branches": [
              {
                "getUserProfileBranch": {
                  "steps": [
                    {
                      "getUserProfile": {
                        "call": "http.get",
                        "args": {
                          "url": "${\"https://example.com/users/\" + input.userId}"
                        },
                        "result": "userProfile"
                      }
                    }
                  ]
                }
              },
              {
                "getRecentItemsBranch": {
                  "steps": [
                    {
                      "getRecentItems": {
                        "try": {
                          "call": "http.get",
                          "args": {
                            "url": "${\"https://example.com/items?userId=\" + input.userId}"
                          },
                          "result": "recentItems"
                        },
                        "except": {
                          "as": "e",
                          "steps": [
                            {
                              "ignoreError": {
                                "assign": [
                                  {
                                    "recentItems": []
                                  }
                                ]
                              }
                            }
                          ]
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      }
    ]
  }
}

并行处理项(使用并行循环)

如果您需要对列表中的每一项执行相同的操作,可以完成 使用并行循环更快地完成执行。并行循环允许 并行执行多次循环迭代。请注意,不同于 常规 for 循环,迭代可以 可按任意顺序执行

在以下示例中,系统会以单个 ID 的形式处理一组用户通知, 并行 for 循环:

YAML

main:
  params: [input]
  steps:
    - sendNotifications:
        parallel:
          for:
            value: notification
            in: ${input.notifications}
            steps:
              - notify:
                  call: http.post
                  args:
                    url: https://example.com/sendNotification
                    body:
                      notification: ${notification}

JSON

{
  "main": {
    "params": [
      "input"
    ],
    "steps": [
      {
        "sendNotifications": {
          "parallel": {
            "for": {
              "value": "notification",
              "in": "${input.notifications}",
              "steps": [
                {
                  "notify": {
                    "call": "http.post",
                    "args": {
                      "url": "https://example.com/sendNotification",
                      "body": {
                        "notification": "${notification}"
                      }
                    }
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }
}

汇总数据(使用并行循环)

您可以在从操作中收集数据的同时处理一组项 对每项内容执行的操作例如,您可能想跟踪 或者维护一个出错项的列表。

在以下示例中,针对一个公共 BigQuery 的 10 个单独查询 每个数据集都会返回一个文档或一组文档中的单词数。答 共享变量 允许字词计数累积,并在所有迭代之后读取 。在计算完所有文档的字数之后, 就会返回总数

YAML

# Use a parallel loop to make ten queries to a public BigQuery dataset and
# use a shared variable to accumulate a count of words; after all iterations
# complete, return the total number of words across all documents
main:
  params: [input]
  steps:
    - init:
        assign:
          - numWords: 0
          - corpuses:
              - sonnets
              - various
              - 1kinghenryvi
              - 2kinghenryvi
              - 3kinghenryvi
              - comedyoferrors
              - kingrichardiii
              - titusandronicus
              - tamingoftheshrew
              - loveslabourslost
    - runQueries:
        parallel:  # 'numWords' is shared so it can be written within the parallel loop
          shared: [numWords]
          for:
            value: corpus
            in: ${corpuses}
            steps:
              - runQuery:
                  call: googleapis.bigquery.v2.jobs.query
                  args:
                    projectId: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
                    body:
                      useLegacySql: false
                      query: ${"SELECT COUNT(DISTINCT word) FROM `bigquery-public-data.samples.shakespeare` " + " WHERE corpus='" + corpus + "' "}
                  result: query
              - add:
                  assign:
                    - numWords: ${numWords + int(query.rows[0].f[0].v)}  # first result is the count
    - done:
        return: ${numWords}

JSON

{
  "main": {
    "params": [
      "input"
    ],
    "steps": [
      {
        "init": {
          "assign": [
            {
              "numWords": 0
            },
            {
              "corpuses": [
                "sonnets",
                "various",
                "1kinghenryvi",
                "2kinghenryvi",
                "3kinghenryvi",
                "comedyoferrors",
                "kingrichardiii",
                "titusandronicus",
                "tamingoftheshrew",
                "loveslabourslost"
              ]
            }
          ]
        }
      },
      {
        "runQueries": {
          "parallel": {
            "shared": [
              "numWords"
            ],
            "for": {
              "value": "corpus",
              "in": "${corpuses}",
              "steps": [
                {
                  "runQuery": {
                    "call": "googleapis.bigquery.v2.jobs.query",
                    "args": {
                      "projectId": "${sys.get_env(\"GOOGLE_CLOUD_PROJECT_ID\")}",
                      "body": {
                        "useLegacySql": false,
                        "query": "${\"SELECT COUNT(DISTINCT word) FROM `bigquery-public-data.samples.shakespeare` \" + \" WHERE corpus='\" + corpus + \"' \"}"
                      }
                    },
                    "result": "query"
                  }
                },
                {
                  "add": {
                    "assign": [
                      {
                        "numWords": "${numWords + int(query.rows[0].f[0].v)}"
                      }
                    ]
                  }
                }
              ]
            }
          }
        }
      },
      {
        "done": {
          "return": "${numWords}"
        }
      }
    ]
  }
}

后续步骤