Panoramica dell'API .NET Framework di Hub eventiEvent Hubs .NET Framework API overview

In questo articolo vengono riepilogati alcune delle principali API client .NET Framework di Hub eventi.This article summarizes some of the key Event Hubs .NET Framework client APIs. Esistono due categorie: API di runtime e gestione.There are two categories: management and run-time APIs. Le API di runtime si compongono di tutte le operazioni necessarie per inviare e ricevere un messaggio.Run-time APIs consist of all operations needed to send and receive a message. Operazioni di gestione consentono di gestire lo stato dell'entità di Hub eventi per la creazione, aggiornamento ed eliminazione di entità.Management operations enable you to manage an Event Hubs entity state by creating, updating, and deleting entities.

Scenari di monitoraggio comprendono gestione e in fase di esecuzione.Monitoring scenarios span both management and run-time. Per la documentazione di riferimento dettagliata sulle API .NET, vedere i riferimenti .NET del bus di servizio e API EventProcessorHost.For detailed reference documentation on the .NET APIs, see the Service Bus .NET and EventProcessorHost API references.

API di gestioneManagement APIs

Per eseguire le operazioni di gestione riportate di seguito sono necessarie autorizzazioni di gestione per lo spazio dei nomi di Hub eventi:To perform the following management operations, you must have Manage permissions on the Event Hubs namespace:

CreateCreate

// Create the event hub
var ehd = new EventHubDescription(eventHubName);
ehd.PartitionCount = SampleManager.numPartitions;
await namespaceManager.CreateEventHubAsync(ehd);

AggiornamentoUpdate

var ehd = await namespaceManager.GetEventHubAsync(eventHubName);

// Create a customer SAS rule with Manage permissions
ehd.UserMetadata = "Some updated info";
var ruleName = "myeventhubmanagerule";
var ruleKey = SharedAccessAuthorizationRule.GenerateRandomKey();
ehd.Authorization.Add(new SharedAccessAuthorizationRule(ruleName, ruleKey, new AccessRights[] {AccessRights.Manage, AccessRights.Listen, AccessRights.Send} )); 
await namespaceManager.UpdateEventHubAsync(ehd);

DeleteDelete

await namespaceManager.DeleteEventHubAsync("event hub name");

API di runtimeRun-time APIs

Crea editoreCreate publisher

// EventHubClient model (uses implicit factory instance, so all links on same connection)
var eventHubClient = EventHubClient.Create("event hub name");

Pubblica messaggioPublish message

// Create the device/temperature metric
var info = new MetricEvent() { DeviceId = random.Next(SampleManager.NumDevices), Temperature = random.Next(100) };
var data = new EventData(new byte[10]); // Byte array
var data = new EventData(Stream); // Stream 
var data = new EventData(info, serializer) //Object and serializer 
{
    PartitionKey = info.DeviceId.ToString()
};

// Set user properties if needed
data.Properties.Add("Type", "Telemetry_" + DateTime.Now.ToLongTimeString());

// Send single message async
await client.SendAsync(data);

Crea consumerCreate consumer

// Create the Event Hubs client
var eventHubClient = EventHubClient.Create(EventHubName);

// Get the default consumer group
var defaultConsumerGroup = eventHubClient.GetDefaultConsumerGroup();

// All messages
var consumer = await defaultConsumerGroup.CreateReceiverAsync(partitionId: index);

// From one day ago
var consumer = await defaultConsumerGroup.CreateReceiverAsync(partitionId: index, startingDateTimeUtc:DateTime.Now.AddDays(-1));

// From specific offset, -1 means oldest
var consumer = await defaultConsumerGroup.CreateReceiverAsync(partitionId: index,startingOffset:-1); 

Utilizzare messaggioConsume message

var message = await consumer.ReceiveAsync();

// Provide a serializer
var info = message.GetBody<Type>(Serializer)

// Get a byte[]
var info = message.GetBytes(); 
msg = UnicodeEncoding.UTF8.GetString(info);

API host processore di eventiEvent Processor Host APIs

Queste API garantiscono resilienza ai processi di lavoro che possono diventare non disponibili, distribuendo tuttavia partizioni tra i ruoli di lavoro disponibili.These APIs provide resiliency to worker processes that may become unavailable, by distributing partitions across available workers.

// Checkpointing is done within the SimpleEventProcessor and on a per-consumerGroup per-partition basis, workers resume from where they last left off.
// Use the EventData.Offset value for checkpointing yourself, this value is unique per partition.

var eventHubConnectionString = System.Configuration.ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
var blobConnectionString = System.Configuration.ConfigurationManager.AppSettings["AzureStorageConnectionString"]; // Required for checkpoint/state

var eventHubDescription = new EventHubDescription(EventHubName);
var host = new EventProcessorHost(WorkerName, EventHubName, defaultConsumerGroup.GroupName, eventHubConnectionString, blobConnectionString);
await host.RegisterEventProcessorAsync<SimpleEventProcessor>();

// To close
await host.UnregisterEventProcessorAsync();

L'interfaccia IEventProcessor è definita come segue:The IEventProcessor interface is defined as follows:

public class SimpleEventProcessor : IEventProcessor
{
    IDictionary<string, string> map;
    PartitionContext partitionContext;

    public SimpleEventProcessor()
    {
        this.map = new Dictionary<string, string>();
    }

    public Task OpenAsync(PartitionContext context)
    {
        this.partitionContext = context;

        return Task.FromResult<object>(null);
    }

    public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
    {
        foreach (EventData message in messages)
        {
            // Process messages here
        }

        // Checkpoint when appropriate
        await context.CheckpointAsync();

    }

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

Passaggi successiviNext steps

Per altre informazioni sugli scenari di Hub eventi, visitare i collegamenti seguenti:To learn more about Event Hubs scenarios, visit these links:

I riferimenti API .NET sono qui:The .NET API references are here: