上篇博文中,我們介紹了Azure Event Hub的一些基本概念和架構:
Azure Event Hub 技術研究系列1-Event Hub入門篇
本篇文章中,我們繼續深入研究,了解Azure Event Hub的建立、程式設計SDK,實作将事件發送到雲端的Azure Event Hub。
一、Azure Portal中建立Event Hub
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuQjM3UTN1kTO1ETLycTN1IzN1EDM3ETNwcTMwITL1ITNzIzLcVDM3EDMy8CX1ITNzIzLcd2bsJ2Lc12bj5ycn9Gbi52YuUTMwIzcldWYtl2Lc9CX6MHc0RHaiojIsJye.png)
二、通過Event Hub的SDK将事件發送到Event Hub
建立一個Console工程:EventHubSend
添加Nuget:
Microsoft.Azure.EventHubs
using Microsoft.Azure.EventHubs;
using System.Text;
using System.Threading.Tasks;
添加常量作為事件中心連接配接字元串和實體路徑(單個事件中心名稱)
private static EventHubClient eventHubClient;
private const string EhConnectionString = "{Event Hubs connection string}"; //第一步拷貝的連接配接字元串
private const string EhEntityPath = "{Event Hub path/name}"; //MyEventHub
新加MainAsync函數
private static async Task MainAsync(string[] args)
{
var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString)
{
EntityPath = EhEntityPath
};
eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
await SendEvents(100);
await eventHubClient.CloseAsync();
Console.WriteLine("Press ENTER to exit.");
Console.ReadLine();
}
将100個事件消息發送到EventHub方法:SendEvents
/// <summary>
/// 建立100個消息事件,異步發送到EventHub
/// </summary>
/// <param name="count">個數</param>
/// <returns></returns>
private static async Task SendEvents(int count)
{
for (var i = 0; i < count; i++)
{
try
{
var eventEntity = $"Event {i}";
Console.WriteLine($"Sending Event: {eventEntity}");
await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(eventEntity)));
}
catch (Exception exception)
{
Console.WriteLine($"{DateTime.Now} > Exception: {exception.Message}");
}
await Task.Delay(10);
}
Console.WriteLine($"{count} messages sent.");
}
在Main函數中添加:
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
Run:
發現錯誤了:The messaging entity 'sb://myeventhubtest.servicebus.chinacloudapi.cn/MyEventHub' could not be found.
MyEventHub這個是我們在代碼中指定的。
private const string EhEntityPath = "MyEventHub"; //MyEventHub
這個是否需要在Azure Portal中提前建立好?
再次Run:
這次可以了。
周國慶
2017/5/17