在azure中存储收到的消息

时间:2018-06-13 13:57:50

标签: c# .net azure azure-iot-hub azure-servicebus-topics

我在C#中有一个简单的邮件发件人

public static async Task SendMessageToTopic(string serviceBusConnectionString, string topic, string message)
{
    const int numberOfMessages = 10;
    topicClient = new TopicClient(serviceBusConnectionString, topic);

    Console.WriteLine("======================================================");
    Console.WriteLine("Press ENTER key to exit after sending all the messages.");
    Console.WriteLine("======================================================");

    // Send messages.
    await SendMessagesAsync(message);

}

static async Task SendMessagesAsync(string message)
{
    try
    {
            var encodedMessage = new Message(Encoding.UTF8.GetBytes(message));

            // Write the body of the message to the console.
            Console.WriteLine($"Sending message: {encodedMessage}");

            // Send the message to the topic.
            await topicClient.SendAsync(encodedMessage);

    }
    catch (Exception exception)
    {
        Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
    }
}

另一方面,我有一个简单的接收器应用程序,一切运行良好。 现在,我想将我的消息(例如整数)存储到Azure存储中,以便稍后绘制它们。我按照此处所述设置了端点和路由https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-store-data-in-azure-table-storage#verify-your-message-in-your-storage-container 但看起来我的容器是空的(我使用Azure Storage Explorer来查看它)

1 个答案:

答案 0 :(得分:1)

我认为有些事情需要澄清。 Service Bus可用作Azure IoT Hub的其他端点之一。 IoT Hub目前支持Azure存储容器,事件中心,服务总线队列和服务总线主题作为附加端点.IoT Hub需要对这些服务端点进行写入访问或配置(通过Azure门户)以使邮件路由正常工作。有关如何understand IoT Hub Endpointsconfigure message routing with Azure IoT Hub的更多信息。您设置的端点是IoT集线器而非服务总线。

Service Bus本身不支持将收到的消息路由到存储容器或其他端点。如果要存储收到的Service Bus消息,可以使用Azure Service Bus bindings for Azure Functions。Azure Functions支持Service Bus队列和主题的触发和输出绑定。此blog显示了如何在运行时使用Azure Functions绑定动态路由队列。

服务总线主题触发器示例(run.csx)的C#:

#r "Microsoft.WindowsAzure.Storage"

using System;
using System.Configuration;
using System.Net;
using System.Text;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

public static async Task Run(string mySbMsg, TraceWriter log)
{
    log.Info($"C# ServiceBus topic trigger function processed message: {mySbMsg}");

    string connectionString="{storage acount connectionString}";
    CloudStorageAccount storageAccount;
    CloudBlobClient client;
    CloudBlobContainer container;
    CloudBlockBlob blob;

    storageAccount = CloudStorageAccount.Parse(connectionString);

    client = storageAccount.CreateCloudBlobClient();

    container = client.GetContainerReference("container01");

    await container.CreateIfNotExistsAsync();

    blob = container.GetBlockBlobReference(DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".json");
    blob.Properties.ContentType = "application/json";

    using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(mySbMsg)))
    {
        await blob.UploadFromStreamAsync(stream);
    }
}