Esempio n. 1
0
        public static async Task Run([EventHubTrigger("new-distributer", Connection = "EventHubConnectionAppSetting")] Azure.Messaging.EventHubs.EventData[] events, ILogger log)
        {
            string connectionString = Environment.GetEnvironmentVariable("EventHubConnectionAppSetting");
            string eventHubName     = "reciver1";
            var    exceptions       = new List <Exception>();

            // Create a producer client that you can use to send events to an event hub
            var producerClient = new EventHubProducerClient(connectionString, eventHubName);

            // Create a batch of events
            using Azure.Messaging.EventHubs.Producer.EventDataBatch eventBatch = await producerClient.CreateBatchAsync();

            // Add events to the batch. An event is a represented by a collection of bytes and metadata.
            eventBatch.TryAdd(new Azure.Messaging.EventHubs.EventData(Encoding.UTF8.GetBytes("First event")));
            eventBatch.TryAdd(new Azure.Messaging.EventHubs.EventData(Encoding.UTF8.GetBytes("Second event")));
            eventBatch.TryAdd(new Azure.Messaging.EventHubs.EventData(Encoding.UTF8.GetBytes("Third event")));

            // Use the producer client to send the batch of events to the event hub
            await producerClient.SendAsync(eventBatch);

            Console.WriteLine("A batch of 3 events has been published.");



            foreach (Azure.Messaging.EventHubs.EventData eventData in events)
            {
                try
                {
                    // string messageBody = Encoding.UTF8.GetString(eventData.Body.ToArray,
                    //                                              eventData.Body.Offset,
                    //                                              eventData.Body.Count);

                    // // Replace these two lines with your processing logic.
                    // log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
                    await Task.Yield();
                }
                catch (Exception e)
                {
                    // We need to keep processing the rest of the batch - capture this exception and continue.
                    // Also, consider capturing details of the message that failed processing so it can be processed again later.
                    exceptions.Add(e);
                }
            }

            // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

            if (exceptions.Count > 1)
            {
                throw new AggregateException(exceptions);
            }

            if (exceptions.Count == 1)
            {
                throw exceptions.Single();
            }
        }
        /// <summary>
        ///   Sends a set of events to the associated Event Hub using a batched approach.
        /// </summary>
        ///
        /// <param name="eventBatch">The set of event data to send. A batch may be created using <see cref="CreateBatchAsync(CancellationToken)" />.</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        ///
        /// <seealso cref="SendAsync(EventData, CancellationToken)" />
        /// <seealso cref="SendAsync(EventData, SendEventOptions, CancellationToken)" />
        /// <seealso cref="SendAsync(IEnumerable{EventData}, CancellationToken)" />
        /// <seealso cref="SendAsync(IEnumerable{EventData}, SendEventOptions, CancellationToken)" />
        /// <seealso cref="CreateBatchAsync(CancellationToken)" />
        ///
        public virtual async Task SendAsync(EventDataBatch eventBatch,
                                            CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(eventBatch, nameof(eventBatch));
            AssertSinglePartitionReference(eventBatch.SendOptions.PartitionId, eventBatch.SendOptions.PartitionKey);

            // Determine the transport producer to delegate the send operation to.  Because sending to a specific
            // partition requires a dedicated client, use (or create) that client if a partition was specified.  Otherwise
            // the default gateway producer can be used to request automatic routing from the Event Hubs service gateway.

            TransportProducer activeProducer;

            if (string.IsNullOrEmpty(eventBatch.SendOptions.PartitionId))
            {
                activeProducer = EventHubProducer;
            }
            else
            {
                // This assertion is intended as an additional check, not as a guarantee.  There still exists a benign
                // race condition where a transport producer may be created after the client has been closed; in this case
                // the transport producer will be force-closed with the associated connection or, worst case, will close once
                // its idle timeout period elapses.

                Argument.AssertNotClosed(IsClosed, nameof(EventHubProducerClient));
                activeProducer = PartitionProducers.GetOrAdd(eventBatch.SendOptions.PartitionId, id => Connection.CreateTransportProducer(id, RetryPolicy));
            }

            using DiagnosticScope scope = CreateDiagnosticScope();

            try
            {
                await activeProducer.SendAsync(eventBatch, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                scope.Failed(ex);
                throw;
            }
        }
Esempio n. 3
0
        private async void publishBatchEvent(string eventHubConnectionString, string eventHubName, JArray entries, ILogger log)
        {
            await using (var producerClient = new EventHubProducerClient(eventHubConnectionString, eventHubName))
            {
                // Create a batch of events
                using Azure.Messaging.EventHubs.Producer.EventDataBatch eventBatch = await producerClient.CreateBatchAsync();

                if (!entries.IsNullOrEmpty())
                {
                    foreach (JToken tok in entries)
                    {
                        string    entrystatus = (string)tok["response"]["status"];
                        EventData dta         = createMsg(entrystatus, tok["resource"]);
                        if (dta != null)
                        {
                            eventBatch.TryAdd(dta);
                        }
                    }
                }
                // Use the producer client to send the batch of events to the event hub
                await producerClient.SendAsync(eventBatch);
            }
        }