我注意到,突然之间,主题不再作为Service Bus的一部分提供。是否可以在Azure函数中将消息写入事件网格主题?
答案 0 :(得分:3)
以下代码段是使用azure函数将遥测流推送到事件模型的示例:
#r "Microsoft.ServiceBus"
#r "Newtonsoft.Json"
using System.Configuration;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;
using Newtonsoft.Json;
// reusable client proxy
static HttpClient client = HttpClientHelper.Client(ConfigurationManager.AppSettings["TopicEndpointEventGrid"], ConfigurationManager.AppSettings["aeg-sas-key"]);
// AF
public static async Task Run(EventData ed, TraceWriter log)
{
log.Info($"C# Event Hub trigger function processed a message:{ed.SequenceNumber}");
//foreach(var prop in ed.SystemProperties)
// log.Info($"{prop.Key} = {prop.Value}");
// fire EventGrid Custom Topic
var egevent = new
{
Id = ed.SequenceNumber.ToString(),
Subject = $"/iothub/events/{ed.SystemProperties["iothub-message-source"] ?? "?"}/{ed.SystemProperties["iothub-connection-device-id"] ?? "?"}",
EventType = "telemetryDataInserted",
EventTime = ed.EnqueuedTimeUtc,
Data = new
{
sysproperties = ed.SystemProperties,
properties = ed.Properties,
body = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(ed.GetBytes()))
}
};
await client.PostAsJsonAsync("", new[] { egevent });
}
// helper
class HttpClientHelper
{
public static HttpClient Client(string address, string key)
{
var client = new HttpClient() { BaseAddress = new Uri(address) };
client.DefaultRequestHeaders.Add("aeg-sas-key", key);
return client;
}
}
function.json:
{
"bindings": [
{
"type": "eventHubTrigger",
"name": "ed",
"direction": "in",
"path": "myIoTHubName",
"connection": "connectionstringIOTHUB",
"consumerGroup": "eventing",
"cardinality": "many"
}
],
"disabled": false
}
请注意,AEG自定义主题的有效负载取决于其 inputSchema 属性。基本上,当前的AEG版本(还包括预览版)允许从以下选择中声明输入模式:
可以找到更多详细信息:
答案 1 :(得分:1)
这是通过Visual Studio代码连接到Azure函数中的Azure事件网格主题的方法。 注意:我不必添加任何function.json文件。
由于Topic就像带有URL的API一样,请创建指向事件数据网格主题URL的HTTP客户端,然后将该主题的Access键添加到HTTP客户端标头中。
HttpClient client = new HttpClient() {
BaseAddress = new Uri(<YOUR_TOPIC_URL>)
};
client.DefaultRequestHeaders.Add("aeg-sas-key", "<YOUR_TOPIC_KEY>");
var egevent = new
{
Id = 1234,
Subject = "SendEmail",
EventType = "SendEmail",
EventTime = DateTime.UtcNow,
Data = <YOUR_MESSAGE>(Could be anything and object or data literals)
};
var x = await client.PostAsJsonAsync("", new[] { egevent });
log.LogInformation(x.ReasonPhrase);
希望这会有所帮助。
答案 2 :(得分:0)
您可以使用Azure Event Grid Nuget package轻松做到这一点:
var failedEvent = new EventGridEvent()
{
Id = Guid.NewGuid().ToString(),
Subject = "create-tenant-failed",
EventType = "create-tenant-failed",
EventTime = DateTime.UtcNow,
Data = reason,
DataVersion = "1.0"
};
var topicHostname = new Uri(FailedEventTopicUrl).Host;
var topicCredentials = new TopicCredentials("my-access-token-from-azure-portal");
var client = new EventGridClient(topicCredentials);
await client.PublishEventsAsync(topicHostname, new List<EventGridEvent>() { failedEvent });