【问题标题】:Azure Event Grid subscription to Console Application on VMAzure 事件网格订阅 VM 上的控制台应用程序
【发布时间】:2019-12-03 15:37:09
【问题描述】:

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

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

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

【问题讨论】:

  • 在 vm 或 azure 外部设置监听器的任何具体原因?这听起来像是使用 azure 函数的一个很好的用例。
  • @Aravind 我有一个可以从 .NET 控制台应用程序运行的 C++ 库,所以我必须在 Azure 上使用 VM。

标签: c# azure azure-eventgrid


【解决方案1】:

一个想法是通过将端点设置到事件网格中的专用 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
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-02-22
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2016-01-26
    • 2019-12-23
    • 2020-02-22
    • 2018-12-12
    • 1970-01-01
    相关资源
    最近更新 更多