在 Lambda 函数中使用带有超时功能的 HttpClient,并在每次访问队列进行 HTTP 请求之前,判断当前时间是否已经接近超时,以避免在队列处于压力巨大状态下出现请求超时的现象。
以下是示例代码:
using System; using System.Net.Http; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents;
[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace AwsLambdaSqsHttpClientTimeout { public class Function { private static HttpClient httpClient; private static DateTime lastAccessTime;
public async Task FunctionHandler(SQSEvent sqsEvent, ILambdaContext context)
{
if (httpClient == null)
{
httpClient = new HttpClient();
}
if (lastAccessTime.AddMinutes(2) < DateTime.Now)
{
// 如果上一次的访问时间距离现在已经超过 2 分钟,则说明已经接近超时
// 这里可以根据具体的需求来进行超时规定
throw new TimeoutException("Timeout!");
}
lastAccessTime = DateTime.Now;
foreach (var message in sqsEvent.Records)
{
await httpClient.PostAsync("https://example.com", new StringContent(message.Body));
}
}
}
}