我这里有一段代码,它在 azure 函数中调用不同的 api。该请求需要一段时间,如果超过 4 分钟,客户端将超时,而不是函数本身超时。这是我的代码
program.cs中的代码
{
client.BaseAddress = new Uri(Environment.GetEnvironmentVariable("MONO_CHAT_URL") ?? throw new NullReferenceException("Mono chat url cannot be null"));
client.DefaultRequestHeaders.Add("keyname", Environment.GetEnvironmentVariable("API_KEY") ?? throw new NullReferenceException("API Key cannot be null"));
client.Timeout = TimeSpan.FromSeconds(9999);
});`
服务中的代码
{
try
{
_logger.LogInformation("Request is send to {BaseUrl}/{Path}", client.BaseAddress, path);
var response = await client.GetFromJsonAsync<T>(path);
if (response != null)
{
_logger.LogInformation("Response recieved for {path}", path);
if (response.GetType() != typeof(T))
{
_logger.LogError("Response with url {BaseUrl}/{Path} is not the correct type", client.BaseAddress , path);
}
}
else
{
_logger.LogError("Response with url {BaseUrl}/{Path} is empty", client.BaseAddress, path);
}
return response;
}
catch (Exception e)
{
_logger.LogError(e, "Could not get data for {path}", path);
throw e;
}
}
本地它工作得很好,因为它从program.cs获取客户端超时,但我有一种感觉,当部署到azure时,azure函数根据此设置自己的客户端超时RequestTimout
HttpClient
230 秒后超时,如果您将其设置为超过 230 秒,由于 Azure 负载均衡器的以下限制,也会超时。
using System;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
namespace _78538129_1
{
public static class DurableFunction
{
[FunctionName("DurableFunction")]
public static async Task RunOrchestrator(
[OrchestrationTrigger] IDurableOrchestrationContext context)
{
// Call Function1
await context.CallActivityAsync("ActivityFunction", null);
}
[FunctionName("ActivityFunction")]
public static async Task CallFunction1([ActivityTrigger] object input, ILogger log)
{
var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMinutes(7);
var response = await httpClient.GetAsync("https://****.azurewebsites.net/api/Function1");
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Function1 failed with status code {response.StatusCode}");
}
log.LogInformation("Function1 called successfully.");
}
[FunctionName("HttpStart_DurableFunction")]
public static async Task<HttpResponseMessage> HttpStart(
[HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestMessage req,
[DurableClient] IDurableOrchestrationClient starter,
ILogger log)
{
// Function input comes from the request content.
string instanceId = await starter.StartNewAsync("DurableFunction", null);
log.LogInformation($"Started orchestration with ID = '{instanceId}'.");
return starter.CreateCheckStatusResponse(req, instanceId);
}
}
}
您可以根据您的需求修改耐用功能。