2

作为负载测试的一部分,我使用 10 个并行线程调用 API 500 次。我想在全局变量(脚本块范围外的计数器)中捕获 API 调用的结果,以便我可以进一步处理以进行验证。

示例-在下面的代码中,我想检查所有 500 API 调用是否成功。

PFB 代码片段-

$invokeAPI =
{
  try {
    $bodyContent = Get-Content $Using:inputFilepath
    $Response = (Invoke-WebRequest -Method 'Post' -Uri $Using:headUri -Headers $Using:blobHeaders  -Body $bodyContent).StatusCode
    
    Write-Host -BackgroundColor Green "status Code :" $Response
  }
  catch [System.Exception] {
    Write-Host -ForegroundColor Red "Exception caught while invoking API :" $_.ErrorDetails.Message
    [int]$_.Exception.Response.StatusCode
  }
} 

1..500 | ForEach-Object -Parallel $invokeAPI -ThrottleLimit 10

<# ToDo...Capture API invocation Result to validate results#>
4

1 回答 1

3

更新:

事实证明,我认为工作是必要的,使我最初的答案过于复杂。但看起来他们不是。看起来它应该像输出到变量一样简单。

将随机测试各种 HTTP 状态的示例脚本:

$invokeAPI = {
  try {
    $statusCode = 200,200,200,200,200,301,400,404,500 | Get-Random;
    (iwr "http://httpbin.org/status/$statusCode").StatusCode;
  }
  catch {
    [int]$_.Exception.Response.StatusCode;
  };
};

$statuscodes = 1..20 | % -Parallel $invokeAPI -ThrottleLimit 5;

$statuscodes;

旧 - 我认为需要乔布斯,结果你不需要,请参阅上面的编辑

改变这个:

1..500 | ForEach-Object -Parallel $invokeAPI -ThrottleLimit 10

对此:

$output = 1..500 | ForEach-Object -Parallel $invokeAPI -ThrottleLimit 10 -AsJob | Wait-Job | Receive-Job
$output

解释:

  • -AsJob- 使其在后台将每个任务作为 PowerShell 作业运行
  • Wait-Job- 等待工作完成
  • Receive-Job- 获取所有工作的返回数据

通过运行-AsJob,它将结果存储在后台。然后,您可以检索作业,这是该作业输出的存储结果。

感谢: https ://devblogs.microsoft.com/powershell/powershell-foreach-object-parallel-feature/

实际上,您的示例与文档中的此示例非常相似: https ://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.1#示例 13--作为作业并行运行

于 2020-12-10T19:01:54.877 回答