gpt4 book ai didi

.net - 如何在 Azure Durable Functions 中插入中间件

转载 作者:行者123 更新时间:2023-12-03 04:40:14 25 4
gpt4 key购买 nike

我想将中间件插入到 Azure Durable Functions v4 (.NET 6),该中间件从 HttpTrigger 获取相关 ID 并将其注册到记录器工厂中,以便它在应用程序洞察中可见。反之亦然;将相关 ID 附加到所有传出请求。我确实有多个 Azure Functions(有些函数相互调用),因此我想通过 CorrelationId 跟踪特定请求。

我尝试过指南 herehere 。然而,它们都有 Program.cs 类并使用该类注册中间件。我只有启动项,它看起来像这样:

public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services
.AddLogging()
.AddHttpClient();
}
}

如何创建一个将相关 ID 获取/附加到请求/响应的解决方案?

类似:...UseMiddleware<CorrelationIdFactory>()

最佳答案

中间件只能注册在 Azure Isolated Functions但不是耐用功能。因为主机构建器无法在持久功能中进行配置。不过,MS 团队刚刚发布了对独立持久功能的支持,可以注册中间件并配置主机构建器。

这里是the released library用于 Azure 隔离持久功能。

This SDK can be used to build Durable Functions apps that run in the Azure Functions .NET Isolated worker process.

以下是如何创建一个 Azure 隔离持久函数,该函数在每个 http 请求上设置 correlationId。 Program.cs 文件:

var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults(workerApplication =>
{
// Register our custom middlewares with the worker

workerApplication.UseWhen<StampHttpHeaderMiddleware>((context) =>
{
// We want to use this middleware only for http trigger invocations.
return context.FunctionDefinition.InputBindings.Values
.First(a => a.Type.EndsWith("Trigger")).Type == "httpTrigger";
});
})
.Build();
//</docsnippet_middleware_register>

host.Run();

StampHttpHeaderMiddleware.cs 文件:

internal sealed class StampHttpHeaderMiddleware : IFunctionsWorkerMiddleware
{
public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
{
var requestData = await context.GetHttpRequestDataAsync();

string correlationId;
if (requestData!.Headers.TryGetValues("x-correlationId", out var values))
{
correlationId = values.First();
}
else
{
correlationId = Guid.NewGuid().ToString();
}

await next(context);

context.GetHttpResponseData()?.Headers.Add("x-correlationId", correlationId);
}
}

这是我们的 Http 触发器,您可以在其中获取/设置关联Id:

static class HelloSequenceUntyped
{
[Function(nameof(StartHelloCitiesUntyped))]
public static async Task<HttpResponseData> StartHelloCitiesUntyped(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
[DurableClient] DurableTaskClient client,
FunctionContext executionContext)
{
ILogger logger = executionContext.GetLogger(nameof(StartHelloCitiesUntyped));

var correlationId = req.Headers.GetValues("x-correlationId").FirstOrDefault();
string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(nameof(HelloCitiesUntyped));
logger.LogInformation("Created new orchestration with instance ID = {instanceId}", instanceId);

return client.CreateCheckStatusResponse(req, instanceId);
}

[Function(nameof(HelloCitiesUntyped))]
public static async Task<string> HelloCitiesUntyped([OrchestrationTrigger] TaskOrchestrationContext context)
{
string result = "";
result += await context.CallActivityAsync<string>(nameof(SayHelloUntyped), "Tokyo") + " ";
result += await context.CallActivityAsync<string>(nameof(SayHelloUntyped), "London") + " ";
result += await context.CallActivityAsync<string>(nameof(SayHelloUntyped), "Seattle");
return result;
}

[Function(nameof(SayHelloUntyped))]
public static string SayHelloUntyped([ActivityTrigger] string cityName, FunctionContext executionContext)
{
ILogger logger = executionContext.GetLogger(nameof(SayHelloUntyped));
logger.LogInformation("Saying hello to {name}", cityName);
return $"Hello, {cityName}!";
}
}

关于.net - 如何在 Azure Durable Functions 中插入中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75236328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com