你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
本快速入门介绍如何通过运行使用 Azure Batch .NET API 的 C# 应用开始使用 Azure Batch。 .NET 应用:
- 将多个输入数据文件上传到 Azure 存储 Blob 容器,以用于批处理任务处理。
- 创建一个包含两个运行 Windows Server 的虚拟机(VM)或计算节点的池。
- 创建一个作业,该作业在节点上运行任务,以使用 Windows 命令行处理每个输入文件。
- 显示任务返回的输出文件。
完成本快速入门后,你将了解 Batch 服务的关键概念,并准备好将 Batch 用于更现实、更大规模的工作负载。
先决条件
拥有有效订阅的 Azure 帐户。 如果你没有帐户,请免费创建一个。
链接到 Azure 存储帐户的 Batch 帐户。 可以使用以下任一方法创建帐户: Azure CLI | Azure 门户 | Bicep | ARM 模板 | Terraform。
适用于 Linux 或 Windows 的 Visual Studio 2019 或更高版本或 .NET 6.0 或更高版本。
运行应用
若要完成本快速入门,请下载或克隆应用,提供帐户值,生成并运行应用,并验证输出。
下载或克隆应用
从 GitHub 下载或克隆 Azure Batch .NET 快速入门 应用。 使用以下命令通过 Git 客户端克隆应用存储库:
git clone https://github.com/Azure-Samples/batch-dotnet-quickstart.git
提供帐户信息
应用需要使用 Batch 和存储帐户名称、帐户密钥值和 Batch 帐户终结点。 可以从 Azure 门户、Azure API 或命令行工具获取此信息。
若要从 Azure 门户获取帐户信息,请执行以下作:
- 在 Azure 搜索栏中,搜索并选择 Batch 帐户名称。
- 在 Batch 帐户页上,从左侧导航中选择 “密钥 ”。
- 在 “密钥 ”页上,复制以下值:
- 批处理帐户
- 帐户终结点
- 主访问密钥
- 存储帐户名称
- 密钥 1
导航到下载的 batch-dotnet-quickstart 文件夹并编辑 Program.cs 中的凭据字符串,以提供复制的值:
// Batch account credentials
private const string BatchAccountName = "<batch account>";
private const string BatchAccountKey = "<primary access key>";
private const string BatchAccountUrl = "<account endpoint>";
// Storage account credentials
private const string StorageAccountName = "<storage account name>";
private const string StorageAccountKey = "<key1>
重要
不建议在应用源中公开帐户密钥以供生产使用。 应限制对凭据的访问,并使用变量或配置文件在代码中引用凭据。 最好将 Batch 和存储帐户密钥存储在 Azure Key Vault 中。
生成并运行应用并查看输出
若要查看 Batch 工作流的操作,请在 Visual Studio 中生成并运行应用程序。 还可以使用命令行 dotnet build 和 dotnet run 命令。
在 Visual Studio 中:
打开 BatchDotNetQuickstart.sln 文件,右键单击 解决方案资源管理器中的解决方案,然后选择“ 生成”。 如果系统提示,请使用 NuGet 包管理器 更新或还原 NuGet 包。
生成完成后,在顶部菜单栏中选择 BatchDotNetQuickstart 以运行应用。
默认配置的典型运行时大约为 5 分钟。 初始池节点设置花费的时间最多。 若要重新运行作业,请从上一次运行中删除作业,但不删除池。 在预配置的池中,作业在几秒钟内完成。
应用返回类似于以下示例的输出:
Sample start: 11/16/2022 4:02:54 PM
Container [input] created.
Uploading file taskdata0.txt to container [input]...
Uploading file taskdata1.txt to container [input]...
Uploading file taskdata2.txt to container [input]...
Creating pool [DotNetQuickstartPool]...
Creating job [DotNetQuickstartJob]...
Adding 3 tasks to job [DotNetQuickstartJob]...
Monitoring all tasks for 'Completed' state, timeout in 00:30:00...
当池的计算节点启动时,会在 Monitoring all tasks for 'Completed' state, timeout in 00:30:00... 出现暂停。 创建任务后,Batch 会将要在池中运行的任务排队。 一旦第一个计算节点可用,第一个任务就会在节点上运行。 可以从 Azure 门户中的 Batch 帐户页监视节点、任务和作业状态。
完成每个任务后,会看到类似于以下示例的输出:
Printing task output.
Task: Task0
Node: tvm-2850684224_3-20171205t000401z
Standard out:
Batch processing began with mainframe computers and punch cards. Today it still plays a central role...
stderr:
...
查看代码
查看代码以了解 Azure Batch .NET 快速入门中的步骤。
创建服务客户端并上传资源文件
为了与存储帐户交互,应用使用适用于 .NET 的 Azure 存储 Blob 客户端库来创建 BlobServiceClient。
var sharedKeyCredential = new StorageSharedKeyCredential(storageAccountName, storageAccountKey); string blobUri = "https://" + storageAccountName + ".blob.core.windows.net"; var blobServiceClient = new BlobServiceClient(new Uri(blobUri), sharedKeyCredential); return blobServiceClient;应用使用
blobServiceClient引用在存储帐户中创建容器,并将数据文件上传到容器。 存储中的文件定义为 Batch ResourceFile 对象,Batch 稍后可以下载到计算节点。List<string> inputFilePaths = new() { "taskdata0.txt", "taskdata1.txt", "taskdata2.txt" }; var inputFiles = new List<ResourceFile>(); foreach (var filePath in inputFilePaths) { inputFiles.Add(UploadFileToContainer(containerClient, inputContainerName, filePath)); }该应用创建一个 BatchClient 对象,用于创建和管理 Batch 池、作业和任务。 Batch 客户端使用共享密钥身份验证。 Batch 还支持Microsoft Entra 身份验证。
var cred = new BatchSharedKeyCredentials(BatchAccountUrl, BatchAccountName, BatchAccountKey); using BatchClient batchClient = BatchClient.Open(cred); ...
创建计算节点池
若要创建 Batch 池,应用使用 BatchClient.PoolOperations.CreatePool 方法设置节点数、VM 大小和池配置。 下面的 VirtualMachineConfiguration 对象指定了对 Windows Server 市场映像的 ImageReference。 Batch 支持各种 Windows Server 和 Linux 市场 OS 映像,还支持自定义 VM 映像。
PoolNodeCount和PoolVMSize VM 大小是定义的常量。 该应用创建两个 Standard_A1_v2 节点的集群。 就此快速入门而言,此节点大小在性能与成本之间达成了很好的平衡。
Commit 方法将池提交到 Batch 服务。
private static VirtualMachineConfiguration CreateVirtualMachineConfiguration(ImageReference imageReference)
{
return new VirtualMachineConfiguration(
imageReference: imageReference,
nodeAgentSkuId: "batch.node.windows amd64");
}
private static ImageReference CreateImageReference()
{
return new ImageReference(
publisher: "MicrosoftWindowsServer",
offer: "WindowsServer",
sku: "2016-datacenter-smalldisk",
version: "latest");
}
private static void CreateBatchPool(BatchClient batchClient, VirtualMachineConfiguration vmConfiguration)
{
try
{
CloudPool pool = batchClient.PoolOperations.CreatePool(
poolId: PoolId,
targetDedicatedComputeNodes: PoolNodeCount,
virtualMachineSize: PoolVMSize,
virtualMachineConfiguration: vmConfiguration);
pool.Commit();
}
...
创建批处理作业
批处理作业是一个或多个任务的逻辑分组。 该作业包含这些任务的公用设置,例如优先级以及运行任务的池。
应用使用 BatchClient.JobOperations.CreateJob 方法在池中创建作业。 Commit 方法将作业提交到 Batch 服务。 作业一开始没有任务。
try
{
CloudJob job = batchClient.JobOperations.CreateJob();
job.Id = JobId;
job.PoolInformation = new PoolInformation { PoolId = PoolId };
job.Commit();
}
...
创建任务
Batch 提供了多种将应用和脚本部署到计算节点的方式。 此应用创建 CloudTask 输入 ResourceFile 对象列表。 每个任务都使用 CommandLine 属性处理输入文件。 Batch 命令行是指定应用或脚本的位置。
以下代码中的命令行运行 Windows type 命令以显示输入文件。 然后,应用使用 AddTask 方法将每个任务添加到作业,该方法将任务排在计算节点上运行。
for (int i = 0; i < inputFiles.Count; i++)
{
string taskId = String.Format("Task{0}", i);
string inputFilename = inputFiles[i].FilePath;
string taskCommandLine = String.Format("cmd /c type {0}", inputFilename);
var task = new CloudTask(taskId, taskCommandLine)
{
ResourceFiles = new List<ResourceFile> { inputFiles[i] }
};
tasks.Add(task);
}
batchClient.JobOperations.AddTask(JobId, tasks);
查看任务输出
该应用创建 TaskStateMonitor 来监视任务并确保它们完成。 当每个任务成功运行时,其输出将写入 stdout.txt。 然后,应用使用 CloudTask.ComputeNodeInformation 属性显示每个已完成任务的 stdout.txt 文件。
foreach (CloudTask task in completedtasks)
{
string nodeId = String.Format(task.ComputeNodeInformation.ComputeNodeId);
Console.WriteLine("Task: {0}", task.Id);
Console.WriteLine("Node: {0}", nodeId);
Console.WriteLine("Standard out:");
Console.WriteLine(task.GetNodeFile(Constants.StandardOutFileName).ReadAsString());
}
清理资源
应用自动删除所创建的存储容器,并允许你选择是否删除 Batch 池和作业。 池和节点会在节点运行时产生费用,即使它们未运行作业也是如此。 如果不再需要池,请将其删除。
不再需要 Batch 帐户和存储帐户时,可以删除包含它们的资源组。 在 Azure 门户中,选择资源组页面顶部的“ 删除资源组 ”。 在 “删除资源组 ”屏幕上,输入资源组名称,然后选择“ 删除”。
后续步骤
在本快速入门中,你运行了一个应用,该应用使用 Batch .NET API 创建 Batch 池、节点、作业和任务。 作业将资源文件上传到存储容器,在节点上运行任务,并显示节点的输出。
现在你已经了解了 Batch 服务的关键概念,可以将 Batch 用于更现实、更大规模的工作负载了。 若要详细了解 Azure Batch 并使用实际应用程序完成并行工作负荷,请继续学习 Batch .NET 教程。