首页 > 解决方案 > Azure 事件网格订阅 VM 上的控制台应用程序

问题描述

我想在 C# 控制台应用程序中订阅 Azure 事件网格,并且该应用程序未托管在 Azure 上(将在 Windows 服务器上)。

其他 C# webapi 项目将触发将托管在 Azure 上的 Azure 事件,但如何订阅(侦听)未托管在 Azure 上的 VM 上的事件?

我应该为上述场景选择哪个端点详细信息?

在此处输入图像描述

标签: c#azureazure-eventgrid

解决方案


一种想法是通过将端点设置到事件网格中的专用 EH(如您的图片中)来将事件推送到事件中心。然后,您可以在您的 VM 上实现侦听器,该侦听器正在从专用端点读取所有事件。

下面是您的脚本应该是什么样子的小代码示例,本质上它只是一个小型控制台应用程序,它从事件中心读取事件并写入控制台:

public class MyEventProcessor : IEventProcessor
{
    private Stopwatch checkpointStopWatch;

    public Task ProcessErrorAsync(PartitionContext context, Exception error)
    {
        Console.WriteLine(error.ToString());
        return Task.FromResult(true);
    }

    async Task IEventProcessor.CloseAsync(PartitionContext context, CloseReason reason)
    {
        if (reason == CloseReason.Shutdown)
        {
            await context.CheckpointAsync();
        }
    }

    Task IEventProcessor.OpenAsync(PartitionContext context)
    {
        var eventHubPartitionId = context.PartitionId;
        Console.WriteLine($"Registered reading from the partition: {eventHubPartitionId} ");
        this.checkpointStopWatch = new Stopwatch();
        this.checkpointStopWatch.Start();
        return Task.FromResult<object>(null);
    }

    //Data comes in here
    async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
    {
        foreach (var eventData in messages)
        {
            var data = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
            Console.WriteLine($"Message Received from partition {context.PartitionId}: {data}");
        }

        await context.CheckpointAsync();
    }
}
class Program
{
    static void Main(string[] args)
    {
        string processorHostName = Guid.NewGuid().ToString();
        var Options = new EventProcessorOptions()
        {
            MaxBatchSize = 1,
        };
        Options.SetExceptionHandler((ex) =>
        {
            System.Diagnostics.Debug.WriteLine($"Exception : {ex}");
        });
        var eventHubCS = "event hub connection string";
        var storageCS = "storage connection string";
        var containerName = "test";
        var eventHubname = "test2";
        EventProcessorHost eventProcessorHost = new EventProcessorHost(eventHubname, "$Default", eventHubCS, storageCS, containerName);
        eventProcessorHost.RegisterEventProcessorAsync<MyEventProcessor>(Options).Wait();

        while(true)
        {
            //do nothing
        }
    }
}

推荐阅读