You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Function中ServiceBusSender运行一日后异常停止问题求助

问题分析与解决方案

核心问题根源

你的问题是长期持有ServiceBusSender实例导致的连接失效:Azure Function实例长期运行时,ServiceBusSender持有的连接会因闲置过久被Azure Service Bus或网络层断开,而旧的Sender实例无法自动重建连接,最终触发超时错误。即使低请求量,只要连接闲置超过阈值就会触发。


具体解决方案

1. 避免长期持有ServiceBusSender实例

当前代码在构造函数中创建ServiceBusSender并长期持有,这会导致连接闲置失效后无法自动恢复。改为每次请求时创建并释放Sender,利用ServiceBusClient的连接池自动管理连接:

修改Run方法代码:

[ProducesResponseType((int)HttpStatusCode.Accepted)]
[ProducesResponseType((int)HttpStatusCode.InternalServerError)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[FunctionName("SMSActivityStopGetHttpListenerV1")]
public async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/smsactivity/stop")] HttpRequest req,
    ILogger log,
    IAzureClientFactory<ServiceBusSender> serviceBusSenderFactory) // 直接在方法中注入工厂
{
    // Simple logic

    HttpResponseMessage response;
    try
    {
        using var sender = serviceBusSenderFactory.CreateClient("SBSender");
        await sender.SendMessageAsync(servicebusMessage);
        response = new HttpResponseMessage(HttpStatusCode.Accepted);
    }
    catch (Exception ex)
    {
        var errorMessage = "发送消息失败";
        response = new HttpResponseMessage(HttpStatusCode.InternalServerError) 
        { 
            Content = new StringContent(errorMessage, Encoding.UTF8, "application/json") 
        };
        SplunkLogger.LogExceptionToSplunk(_logger, _commonMessage, null, correlationId, "SMSActivityStop API failed", ex.Message);
    }
    return response;
}

同时可以移除类中的_sender私有字段和构造函数中对应的注入代码,简化类结构。

2. 调整ServiceBusClient连接闲置超时

默认情况下,ServiceBusClient的连接闲置超时为30分钟,低请求量场景下容易触发连接断开。延长超时时间,避免连接被过早回收:

修改依赖注入配置:

builder.Services.AddAzureClients(clientsBuilder =>
{
    clientsBuilder.AddServiceBusClient(appConfig.GetValue<string>("CRMSBActivityConnectionString"))
    .ConfigureOptions(options =>
      {
          options.RetryOptions.Delay = TimeSpan.FromMilliseconds(50);
          options.RetryOptions.MaxDelay = TimeSpan.FromSeconds(10);
          options.RetryOptions.MaxRetries = 5;
          options.RetryOptions.Mode = ServiceBusRetryMode.Exponential; // 改为指数退避重试
          options.ConnectionIdleTimeout = TimeSpan.FromHours(2); // 延长连接闲置超时到2小时
      });
    clientsBuilder.AddClient<ServiceBusSender, ServiceBusClientOptions>((_, _, provider) =>
        provider.GetService<ServiceBusClient>().CreateSender(appConfig.GetValue<string>("CRMSBActivityTopicName"))
    ).WithName("SBSender");
});

3. 升级SDK到最新稳定版

你当前使用的7.16.1版本可能存在已知的连接管理问题,升级到最新的7.x稳定版(如7.20+),官方修复了多个连接相关的bug,能提升稳定性。

4. 优化重试策略适配连接重建

将重试模式改为指数退避,并增加重试次数和最大延迟,给连接重建足够的时间:

options.RetryOptions.Mode = ServiceBusRetryMode.Exponential;
options.RetryOptions.MaxRetries = 5;
options.RetryOptions.MaxDelay = TimeSpan.FromSeconds(10);

验证方案

  1. 部署修改后的代码,观察是否还会出现每日超时问题
  2. 若问题仍存在,可尝试将Azure Function从消费计划切换到高级计划,避免消费计划的实例休眠/网络回收机制影响连接稳定性

内容的提问来源于stack exchange,提问作者Preppern

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 06:15:04