如何在MVC应用程序中正确处理azure事件集线器接收器?

时间:2016-10-27 17:36:40

标签: c# asp.net-mvc azure azure-eventhub

我在Microsoft Azure Event Hub上做了一个小项目。我需要将我的Azure订阅的活动日志显示给MVC应用程序。

我能够将事件日志流式传输到服务总线,并且在从EventHubReceiver接收数据时遇到问题。如果没有数据,接收器似乎就会冻结。我理解这是因为eventhubs使用的pub子架构,但我想控制流程,因为我使用的是MVC应用程序。

现在我使用了CancellationToken并明确等待6秒钟让EventReceiver接收所有消息。有更好的方法吗?

public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            var cts = new CancellationTokenSource();
            var list = new List<Record>();
            for (int i = 0; i < 4; i++)
            {
                Task.Factory.StartNew((state) =>
                {
                    var factory = MessagingFactory.CreateFromConnectionString("Endpoint=sb://xcvxcv.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xcvxcvxvxvxcvxcccccccccccccccccccccccccc;TransportType=Amqp");
                    var client = factory.CreateEventHubClient("insights-operational-logs");

                    var group = client.GetDefaultConsumerGroup();
                    var receiver = group.CreateReceiver(state.ToString(), DateTime.Now.AddDays(-1));


                    while (true)
                    {
                        if (cts.IsCancellationRequested)
                        {
                            receiver.Close();
                            break;
                        }
                        var messages = receiver.Receive(10);
                        foreach (var message in messages)
                        {
                            var logMessage = Newtonsoft.Json.JsonConvert.DeserializeObject<LogEventMessage>(Encoding.Default.GetString(message.GetBytes()));
                            list.AddRange(logMessage.records);
                        }
                    }
                }, i);
            }
            Thread.Sleep(5000);
            cts.Cancel();
            return View(list.OrderBy(o => o.time));
        }
    }

1 个答案:

答案 0 :(得分:0)

我会考虑在ProcessEventsAsync中实现EventProcessorHost接口并控制流程。

https://azure.microsoft.com/en-us/documentation/articles/event-hubs-csharp-ephcs-getstarted/