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

如何实现检查Event Hub与Queue的Azure Function健康检查端点

实现Azure Function健康检查端点(Event Hub + Queue状态检测)

核心思路

健康检查的关键是主动验证资源的可访问性,而非仅依赖配置。针对Event Hub和Queue,分别通过轻量API调用确认连通性与可用性:只要任一资源检测失败,返回500状态码;全部正常则返回200。

具体实现步骤(C#示例)

1. 安装依赖NuGet包

Install-Package Azure.Messaging.EventHubs
Install-Package Azure.Storage.Queues

2. 完整代码实现

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Azure.Messaging.EventHubs;
using Azure.Storage.Queues;
using System;
using System.Threading.Tasks;

public static class HealthCheckFunction
{
    [FunctionName("HealthCheck")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "health")] HttpRequest req,
        ILogger log)
    {
        bool isHealthy = true;
        var eventHubStatus = "Healthy";
        var queueStatus = "Healthy";

        // 检测Event Hub连通性
        try
        {
            var eventHubClient = new EventHubClient(Environment.GetEnvironmentVariable("EventHubConnectionString"));
            await eventHubClient.GetNamespacePropertiesAsync();
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Event Hub health check failed");
            eventHubStatus = $"Failed: {ex.Message}";
            isHealthy = false;
        }

        // 检测Queue连通性
        try
        {
            var queueClient = new QueueClient(
                Environment.GetEnvironmentVariable("QueueConnectionString"), 
                Environment.GetEnvironmentVariable("QueueName"));
            await queueClient.GetPropertiesAsync();
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Queue health check failed");
            queueStatus = $"Failed: {ex.Message}";
            isHealthy = false;
        }

        var response = new
        {
            Status = isHealthy ? "Healthy" : "Unhealthy",
            EventHubStatus = eventHubStatus,
            QueueStatus = queueStatus
        };

        return isHealthy 
            ? new OkObjectResult(response) 
            : new StatusCodeResult(StatusCodes.Status500InternalServerError);
    }
}

3. 关键细节说明

  • 轻量检测操作:选择GetNamespacePropertiesAsync(Event Hub)和GetPropertiesAsync(Queue),仅验证连通性与权限,无消息读写开销,适合健康检查场景。
  • 敏感信息配置:将连接字符串、队列名存入Azure Function应用设置,避免硬编码。
  • 权限要求:确保Function使用的服务主体(或连接字符串)拥有Event Hub的Microsoft.EventHub/namespaces/read权限、Queue的Microsoft.Storage/storageAccounts/queues/read权限,防止因权限不足误判。

Python示例代码

import os
import azure.functions as func
from azure.eventhub import EventHubConsumerClient
from azure.storage.queue import QueueClient

def main(req: func.HttpRequest) -> func.HttpResponse:
    is_healthy = True
    eventhub_status = "Healthy"
    queue_status = "Healthy"

    # 检测Event Hub
    try:
        client = EventHubConsumerClient.from_connection_string(
            conn_str=os.environ["EventHubConnectionString"],
            consumer_group="$Default"
        )
        with client:
            client.get_eventhub_properties()
    except Exception as e:
        eventhub_status = f"Failed: {str(e)}"
        is_healthy = False

    # 检测Queue
    try:
        queue_client = QueueClient.from_connection_string(
            conn_str=os.environ["QueueConnectionString"],
            queue_name=os.environ["QueueName"]
        )
        queue_client.get_queue_properties()
    except Exception as e:
        queue_status = f"Failed: {str(e)}"
        is_healthy = False

    response_body = {
        "Status": "Healthy" if is_healthy else "Unhealthy",
        "EventHubStatus": eventhub_status,
        "QueueStatus": queue_status
    }

    return func.HttpResponse(
        str(response_body),
        status_code=200 if is_healthy else 500,
        mimetype="application/json"
    )

验证方法

部署后访问https://<你的函数应用名>.azurewebsites.net/api/health:

  • 资源正常时返回200状态码及健康状态JSON
  • 任一资源异常时返回500状态码及异常详情

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:40:35