Quantcast
Channel: かずきのBlog@hatena
Viewing all articles
Browse latest Browse all 1387

IoT HubでEventProcessorHostを使ってメッセージを受信する

$
0
0

IEventProcessorを作って。

class EventProcessor : IEventProcessor
{
    private Stopwatch stopwatch;

    public async Task CloseAsync(PartitionContext context, CloseReason reason)
    {
        if (reason == CloseReason.Shutdown)
        {
            await context.CheckpointAsync();
        }
    }

    public Task OpenAsync(PartitionContext context)
    {
        stopwatch = Stopwatch.StartNew();
        return Task.FromResult(0);
    }

    public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
    {
        var convertedMessages = messages
            .Select(x => x.GetBytes())
            .Select(x => Encoding.UTF8.GetString(x))
            .Select(x => JsonConvert.DeserializeObject<ReceiveData>(x));

        foreach (var p in convertedMessages)
        {
            Console.WriteLine($"{p.Name} {p.Age}");
        }

        if (this.stopwatch.Elapsed.TotalMinutes >= 5)
        {
            await context.CheckpointAsync();
        }
    }
}

class ReceiveData
{
    publicstring Name { get; set; }
    publicint Age { get; set; }
}

EventProcessorHostを作るだけ。基本的にEventHubと一緒です。messages/eventsが固定っぽいかな。

conststring IoTHubConnectionString = "IoTHubの接続文字列"staticreadonlystring StorageConnectionString = "Storageの接続文字列"staticvoid Main()
{
    var eventProcessorHost = new EventProcessorHost(
        Guid.NewGuid().ToString(),
        "messages/events",
        EventHubConsumerGroup.DefaultGroupName,
        IoTHubConnectionString,
        StorageConnectionString,
        "messages-events");
    eventProcessorHost.RegisterEventProcessorAsync<EventProcessor>().Wait();

    var host = new JobHost();
    // The following code ensures that the WebJob will be running continuously
    host.RunAndBlock();
}

Viewing all articles
Browse latest Browse all 1387

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>