c# - Azure 事件网格订阅 VM 上的控制台应用程序
问题描述
我想在 C# 控制台应用程序中订阅 Azure 事件网格,并且该应用程序未托管在 Azure 上(将在 Windows 服务器上)。
其他 C# webapi 项目将触发将托管在 Azure 上的 Azure 事件,但如何订阅(侦听)未托管在 Azure 上的 VM 上的事件?
我应该为上述场景选择哪个端点详细信息?
解决方案
一种想法是通过将端点设置到事件网格中的专用 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
}
}
}
推荐阅读
- git - 无法提交文件夹:错误:pathspec 'message' 与 git 已知的任何文件都不匹配
- kivy - Kivy 没有打开新窗口
- c++ - C++ 中的多维数组初始化
- python - 使用多个索引加入 DataFrame
- spring - 处理绑定结果注解后如何使用Exceptionhandler注解
- crash - 快速写入数据时领域崩溃
- css - 具有大中心图像的响应式 CSS 网格
- parsing - 布尔表达式语法的有效性
- amazon-web-services - 如何将 Okta 用户关联到特定的 redshift 数据库组?
- javascript - 测试反应组件:Jest 遇到了一个意外的令牌