Lompat ke konten Lompat ke sidebar Lompat ke footer

Add to Queue Share Dead Again

Skip to master content

Azure Service Passenger vehicle customer library for .Net - Version 7.8.0-beta.1

Azure Service Bus allows you to build applications that take advantage of asynchronous messaging patterns using a highly-reliable service to broker messages between producers and consumers. Azure Service Bus provides flexible, brokered messaging betwixt client and server, forth with structured showtime-in, showtime-out (FIFO) messaging, and publish/subscribe capabilities with circuitous routing. If you would like to know more about Azure Service Autobus, you may wish to review: What is Azure Service Bus?

Use the client library for Azure Service Bus to:

  • Transfer business data: leverage messaging for durable exchange of data, such every bit sales or buy orders, journals, or inventory movements.

  • Decouple applications: meliorate reliability and scalability of applications and services, relieving senders and receivers of the need to be online at the same time.

  • Control how messages are candy: support traditional competing consumers for messages using queues or let each consumer their ain instance of a message using topics and subscriptions.

  • Implement complex workflows: bulletin sessions support scenarios that crave message ordering or message deferral.

Source code | Packet (NuGet) | API reference documentation | Product documentation | Migration guide

Getting started

Prerequisites

  • Microsoft Azure Subscription: To apply Azure services, including Azure Service Bus, you'll need a subscription. If you do non take an existing Azure account, you may sign upwardly for a complimentary trial or use your MSDN subscriber benefits when you create an account.

  • Service Bus namespace: To interact with Azure Service Bus, y'all'll also need to accept a namespace available. If you are not familiar with creating Azure resources, yous may wish to follow the step-by-step guide for creating a Service Coach namespace using the Azure portal. There, you tin can likewise find detailed instructions for using the Azure CLI, Azure PowerShell, or Azure Resources Manager (ARM) templates to create a Service bus entity.

  • C# viii.0: The Azure Service Jitney customer library makes use of new features that were introduced in C# 8.0. In order to take advantage of the C# 8.0 syntax, it is recommended that you compile using the .Net Core SDK 3.0 or higher with a language version of latest. It is also possible to compile with the .Internet Core SDK 2.ane.x using a language version of preview.

    Visual Studio users wishing to take full advantage of the C# 8.0 syntax will need to use Visual Studio 2019 or afterward. Visual Studio 2019, including the costless Community edition, tin be downloaded here. Users of Visual Studio 2017 can accept advantage of the C# 8 syntax past making utilize of the Microsoft.Internet.Compilers NuGet package and setting the language version, though the editing experience may not be ideal.

    You can still use the library with previous C# language versions, but will need to manage asynchronous enumerable and asynchronous disposable members manually rather than benefiting from the new syntax. You may yet target any framework version supported by your .NET Core SDK, including earlier versions of .NET Core or the .Internet framework. For more information, run into: how to specify target frameworks.

    Of import Note: In gild to build or run the examples and the samples without modification, use of C# eight.0 is mandatory. You can notwithstanding run the samples if you determine to tweak them for other linguistic communication versions.

To speedily create the needed Service Motorbus resource in Azure and to receive a connection string for them, you tin deploy our sample template by clicking:

Deploy to Azure

Install the parcel

Install the Azure Service Bus client library for .NET with NuGet:

              dotnet add bundle Azure.Messaging.ServiceBus                          

Authenticate the customer

For the Service Jitney client library to interact with a queue or topic, it volition demand to understand how to connect and authorize with information technology. The easiest means for doing and then is to use a connection cord, which is created automatically when creating a Service Motorcoach namespace. If you aren't familiar with shared access policies in Azure, you lot may wish to follow the step-by-step guide to get a Service Double-decker connexion string.

Once you have a connection cord, you can authenticate your client with it.

              // Create a ServiceBusClient that volition authenticate using a connectedness string string connectionString = "<connection_string>"; ServiceBusClient client = new ServiceBusClient(connectionString);                          

To run into how to authenticate using Azure.Identity, view this instance.

ASP.Internet Cadre

To inject ServiceBusClient as a dependency in an ASP.Internet Core app, install the Azure client library integration for ASP.NET Core package.

              dotnet add bundle Microsoft.Extensions.Azure                          

Then register the client in the Startup.ConfigureServices method:

              public void ConfigureServices(IServiceCollection services) {     services.AddAzureClients(builder =>     {         builder.AddServiceBusClient(Configuration.GetConnectionString("ServiceBus"));     });        services.AddControllers(); }                          

To use the preceding code, add together this to your configuration:

              {   "ConnectionStrings": {     "ServiceBus": "<connection_string>"   } }                          

For more details, see Dependency injection with the Azure SDK for .Internet.

Fundamental concepts

In one case you lot've initialized a ServiceBusClient, you can interact with the primary resource types within a Service Jitney Namespace, of which multiple can exist and on which actual message manual takes place, the namespace oft serving equally an application container:

  • Queue: Allows for Sending and Receiving of messages. Ofttimes used for indicate-to-point communication.

  • Topic: As opposed to Queues, Topics are meliorate suited to publish/subscribe scenarios. A topic tin be sent to, just requires a subscription, of which there can be multiple in parallel, to consume from.

  • Subscription: The machinery to consume from a Topic. Each subscription is contained, and receives a copy of each message sent to the topic. Rules and Filters can be used to tailor which letters are received past a specific subscription.

For more information about these resource, see What is Azure Service Bus?.

To interact with these resource, one should exist familiar with the following SDK concepts:

  • A Service Charabanc customer is the principal interface for developers interacting with the Service Bus client library. It serves as the gateway from which all interaction with the library will occur.

  • A Service Autobus sender is scoped to a particular queue or topic, and is created using the Service Autobus client. The sender allows you to send messages to a queue or topic. It also allows for scheduling messages to exist available for delivery at a specified date.

  • A Service Autobus receiver is scoped to a particular queue or subscription, and is created using the Service Double-decker client. The receiver allows you to receive messages from a queue or subscription. It also allows the messages to be settled after receiving them. At that place are four ways of settling messages:

    • Complete - causes the message to be deleted from the queue or topic.
    • Carelessness - releases the receiver's lock on the message allowing for the message to exist received by other receivers.
    • Defer - defers the message from being received past normal means. In gild to receive deferred messages, the sequence number of the message needs to be retained.
    • DeadLetter - moves the message to the Expressionless Alphabetic character queue. This volition forbid the message from being received over again. In order to receive messages from the Expressionless Letter queue, a receiver scoped to the Dead Letter queue is needed.
  • A Service Double-decker session receiver is scoped to a particular session-enabled queue or subscription, and is created using the Service Jitney client. The session receiver is almost identical to the standard receiver, with the deviation being that session direction operations are exposed which only utilize to session-enabled entities. These operations include getting and setting session land, also equally renewing session locks.

  • A Service Charabanc processor is scoped to a particular queue or subscription, and is created using the Service Bus client. The ServiceBusProcessor tin can be idea of as an brainchild around a ready of receivers. It uses a callback model to allow code to exist specified when a message is received and when an exception occurs. It offers automatic completion of processed messages, automatic message lock renewal, and concurrent execution of user specified result handlers. Considering of its feature set, information technology should be the go to tool for writing applications that receive from Service Jitney entities. The ServiceBusReceiver is recommended for more complex scenarios in which the processor is non able to provide the fine-grained command that ane can wait when using the ServiceBusReceiver straight.

  • A Service Bus session processor is scoped to a particular session-enabled queue or subscription, and is created using the Service Bus client. The session processor is almost identical to the standard processor, with the divergence being that session management operations are exposed which only employ to session-enabled entities.

For more concepts and deeper give-and-take, see: Service Bus Avant-garde Features.

Client lifetime

The ServiceBusClient, senders, receivers, and processors are safe to cache and use as a singleton for the lifetime of the application, which is best practice when messages are being sent or received regularly. They are responsible for efficient direction of network, CPU, and memory use, working to proceed usage low during periods of inactivity.

These types are dispensable and calling either DisposeAsync or CloseAsync is required to ensure that network resources and other unmanaged objects are properly cleaned up. It is important to note that when a ServiceBusClient instance is disposed, it will automatically shut and cleanup whatever senders, receivers, and processors that were created using it.

Thread safety

We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is ever safety, even across threads.

Additional concepts

Client options | Handling failures | Diagnostics | Mocking

Examples

  • Send and receive a bulletin
  • Send and receive a batch of messages
  • Complete a bulletin
  • Carelessness a message
  • Defer a message
  • Dead letter a message
  • Using the processor
  • Authenticating with Azure.Identity
  • Working with sessions
  • More samples

Send and receive a message

Bulletin sending is performed using the ServiceBusSender. Receiving is performed using the ServiceBusReceiver.

              cord connectionString = "<connection_string>"; string queueName = "<queue_name>"; // since ServiceBusClient implements IAsyncDisposable nosotros create it with "await using" await using var client = new ServiceBusClient(connectionString);  // create the sender ServiceBusSender sender = customer.CreateSender(queueName);  // create a message that we tin can send. UTF-8 encoding is used when providing a string. ServiceBusMessage bulletin = new ServiceBusMessage("Hullo world!");  // send the message await sender.SendMessageAsync(bulletin);  // create a receiver that we can employ to receive the message ServiceBusReceiver receiver = client.CreateReceiver(queueName);  // the received message is a different blazon every bit information technology contains some service set properties ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync();  // get the message body as a string string trunk = receivedMessage.Body.ToString(); Console.WriteLine(body);                          

Send and receive a batch of messages

There are ii ways of sending several messages at once. The first style of doing this uses safe-batching. With prophylactic-batching, you lot can create a ServiceBusMessageBatch object, which will allow you to attempt to add together letters one at a time to the batch using the TryAdd method. If the message cannot fit in the batch, TryAdd will return imitation.

              // add the messages that we program to send to a local queue Queue<ServiceBusMessage> messages = new Queue<ServiceBusMessage>(); messages.Enqueue(new ServiceBusMessage("Start message")); letters.Enqueue(new ServiceBusMessage("Second message")); messages.Enqueue(new ServiceBusMessage("Third message"));  // create a message batch that we can send // full number of messages to be sent to the Service Bus queue int messageCount = messages.Count;  // while all messages are non sent to the Service Bus queue while (messages.Count > 0) {     // start a new batch     using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();      // add the first bulletin to the batch     if (messageBatch.TryAddMessage(messages.Peek()))     {         // dequeue the message from the .Cyberspace queue once the bulletin is added to the batch         messages.Dequeue();     }     else     {         // if the showtime message can't fit, then it is too big for the batch         throw new Exception($"Message {messageCount - letters.Count} is as well large and cannot be sent.");     }      // add equally many letters every bit possible to the electric current batch     while (letters.Count > 0 && messageBatch.TryAddMessage(letters.Peek()))     {         // dequeue the message from the .NET queue as it has been added to the batch         messages.Dequeue();     }      // now, send the batch     await sender.SendMessagesAsync(messageBatch);      // if there are any remaining letters in the .Cyberspace queue, the while loop repeats }                          

The second mode uses the SendMessagesAsync overload that accepts an IEnumerable of ServiceBusMessage. With this method, nosotros volition attempt to fit all of the supplied messages in a unmarried message batch that nosotros will send to the service. If the messages are too big to fit in a single batch, the operation will throw an exception.

              IList<ServiceBusMessage> messages = new Listing<ServiceBusMessage>(); messages.Add(new ServiceBusMessage("Commencement")); messages.Add(new ServiceBusMessage("Second")); // transport the letters await sender.SendMessagesAsync(messages);                          

Complete a message

In order to remove a message from a queue or subscription, we can phone call the CompleteAsync method.

              string connectionString = "<connection_string>"; cord queueName = "<queue_name>"; // since ServiceBusClient implements IAsyncDisposable we create it with "wait using" expect using var client = new ServiceBusClient(connectionString);  // create the sender ServiceBusSender sender = client.CreateSender(queueName);  // create a bulletin that nosotros tin can send ServiceBusMessage message = new ServiceBusMessage("Hello world!");  // send the message expect sender.SendMessageAsync(message);  // create a receiver that we tin use to receive and settle the bulletin ServiceBusReceiver receiver = client.CreateReceiver(queueName);  // the received message is a unlike type equally it contains some service set properties ServiceBusReceivedMessage receivedMessage = wait receiver.ReceiveMessageAsync();  // complete the bulletin, thereby deleting it from the service await receiver.CompleteMessageAsync(receivedMessage);                          

Abandon a message

Abandoning a message releases our receiver's lock, which allows the message to be received by this or other receivers.

              ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync();  // abandon the message, thereby releasing the lock and allowing it to be received again by this or other receivers await receiver.AbandonMessageAsync(receivedMessage);                          

Defer a message

Deferring a bulletin will preclude it from being received again using the ReceiveMessageAsync or ReceiveMessagesAsync methods. Instead, at that place are divide methods, ReceiveDeferredMessageAsync and ReceiveDeferredMessagesAsync for receiving deferred messages.

              ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync();  // defer the message, thereby preventing the message from being received again without using // the received deferred message API. await receiver.DeferMessageAsync(receivedMessage);  // receive the deferred message by specifying the service fix sequence number of the original // received bulletin ServiceBusReceivedMessage deferredMessage = wait receiver.ReceiveDeferredMessageAsync(receivedMessage.SequenceNumber);                          

Dead letter a message

Dead lettering a message is like to deferring with one main divergence being that messages will be automatically dead lettered by the service after they have been received a certain number of times. Applications can cull to manually expressionless alphabetic character messages based on their requirements. When a bulletin is dead lettered it is actually moved to a subqueue of the original queue. Annotation that the ServiceBusReceiver is used to receive messages from the expressionless letter subqueue regardless of whether or not the main queue is session-enabled.

              ServiceBusReceivedMessage receivedMessage = expect receiver.ReceiveMessageAsync();  // expressionless-letter the message, thereby preventing the message from being received again without receiving from the dead letter queue. await receiver.DeadLetterMessageAsync(receivedMessage);  // receive the expressionless lettered message with receiver scoped to the dead letter queue. ServiceBusReceiver dlqReceiver = client.CreateReceiver(queueName, new ServiceBusReceiverOptions {     SubQueue = SubQueue.DeadLetter }); ServiceBusReceivedMessage dlqMessage = await dlqReceiver.ReceiveMessageAsync();                          

Using the Processor

The ServiceBusProcessor can be thought of as an brainchild around a set of receivers. Information technology uses a callback model to allow lawmaking to be specified when a bulletin is received and when an exception occurs. It offers automatic completion of processed messages, automatic message lock renewal, and concurrent execution of user specified result handlers. Because of its feature fix, it should be the get to tool for writing applications that receive from Service Double-decker entities. The ServiceBusReceiver is recommended for more complex scenarios in which the processor is not able to provide the fine-grained control that one can expect when using the ServiceBusReceiver straight.

              cord connectionString = "<connection_string>"; string queueName = "<queue_name>"; // since ServiceBusClient implements IAsyncDisposable we create it with "await using" expect using var client = new ServiceBusClient(connectionString);  // create the sender ServiceBusSender sender = client.CreateSender(queueName);  // create a set of messages that we can ship ServiceBusMessage[] letters = new ServiceBusMessage[] {     new ServiceBusMessage("First"),     new ServiceBusMessage("Second") };  // ship the message batch await sender.SendMessagesAsync(messages);  // create the options to utilize for configuring the processor var options = new ServiceBusProcessorOptions {     // By default or when AutoCompleteMessages is set to true, the processor volition complete the message afterwards executing the bulletin handler     // Fix AutoCompleteMessages to false to [settle messages](https://docs.microsoft.com/en-us/azure/service-bus-messaging/message-transfers-locks-settlement#peeklock) on your ain.     // In both cases, if the bulletin handler throws an exception without settling the message, the processor will abandon the message.     AutoCompleteMessages = false,      // I tin likewise permit for multi-threading     MaxConcurrentCalls = 2 };  // create a processor that we tin can utilise to process the letters expect using ServiceBusProcessor processor = customer.CreateProcessor(queueName, options);  // configure the message and error handler to use processor.ProcessMessageAsync += MessageHandler; processor.ProcessErrorAsync += ErrorHandler;  async Task MessageHandler(ProcessMessageEventArgs args) {     cord body = args.Message.Torso.ToString();     Console.WriteLine(body);      // we can evaluate application logic and use that to determine how to settle the message.     await args.CompleteMessageAsync(args.Message); }  Task ErrorHandler(ProcessErrorEventArgs args) {     // the error source tells me at what bespeak in the processing an error occurred     Console.WriteLine(args.ErrorSource);     // the fully qualified namespace is bachelor     Console.WriteLine(args.FullyQualifiedNamespace);     // as well as the entity path     Console.WriteLine(args.EntityPath);     Console.WriteLine(args.Exception.ToString());     render Task.CompletedTask; }  // start processing await processor.StartProcessingAsync();  // since the processing happens in the background, we add together a Panel.ReadKey to allow the processing to continue until a cardinal is pressed. Console.ReadKey();                          

Authenticating with Azure.Identity

The Azure Identity library provides piece of cake Azure Active Directory back up for authentication.

              // Create a ServiceBusClient that will cosign through Active Directory cord fullyQualifiedNamespace = "yournamespace.servicebus.windows.cyberspace"; ServiceBusClient client = new ServiceBusClient(fullyQualifiedNamespace, new DefaultAzureCredential());                          

Working with Sessions

Sessions provide a mechanism for group related messages. In order to use sessions, you need to exist working with a session-enabled entity.

  • Sending and receiving session messages
  • Using the session processor

Troubleshooting

Exception handling

Service Bus Exception

A ServiceBusException is triggered when an operation specific to Service Motorbus has encountered an upshot, including both errors inside the service and specific to the client. The exception includes some contextual data to assist in agreement the context of the error and its relative severity. These are:

  • IsTransient : This identifies whether or not the exception is considered recoverable. In the case where information technology was deemed transient, the appropriate retry policy has already been practical and retries were unsuccessful.

  • Reason : Provides a set of well-known reasons for the failure that help to categorize and clarify the root cause. These are intended to allow for applying exception filtering and other logic where inspecting the text of an exception message wouldn't exist ideal. Some key failure reasons are:

    • Service Timeout : This indicates that the Service Charabanc service did not respond to an operation within the expected amount of fourth dimension. This may accept been caused by a transient network issue or service problem. The Service Bus service may or may not have successfully completed the request; the status is not known. It is recommended to attempt to verify the electric current country and retry if necessary.

    • Message Lock Lost : This can occur if the processing takes longer than the lock duration specified at the entity level for a message. If this error occurs consistently, it may be worth increasing the message lock duration. Otherwise, callers can renew the message lock while they are processing the message to ensure that this error doesn't occur.

    • Messaging Entity Not Institute: A Service Bus resource, such as a queue, topic, or subscription could not exist plant by the Service Passenger vehicle service. This may betoken that it has been deleted from the service or that there is an issue with the Service Omnibus service itself.

Reacting to a specific failure reason for the ServiceBusException tin can be accomplished in several ways, such as by applying an exception filter clause every bit role of the catch block:

              try {     // Receive letters using the receiver client } take hold of (ServiceBusException ex) when     (ex.Reason == ServiceBusFailureReason.ServiceTimeout) {     // Accept action based on a service timeout }                          

Other exceptions

For detailed information about the failures represented by the ServiceBusException and other exceptions that may occur, please refer to Service Bus messaging exceptions.

Logging and diagnostics

The Service Bus customer library is fully instrumented for logging information at various levels of particular using the .NET EventSource to emit information. Logging is performed for each operation and follows the pattern of marking the starting point of the operation and either it's completion or exceptions encountered. Additional data that may offer insight is also logged in the context of the associated operation.

The Service Bus client logs are available to any EventListener past opting into the source named "Azure-Messaging-ServiceBus" or opting into all sources that have the trait "AzureEventSource". To make capturing logs from the Azure client libraries easier, the Azure.Cadre library used past Service Bus offers an AzureEventSourceListener. More than data tin exist found in the Azure.Cadre Diagnostics sample.

The Service Double-decker customer library is likewise instrumented for distributed tracing using Application Insights or OpenTelemetry. More information tin can be establish in the Azure.Core Diagnostics sample.

Next steps

Beyond the introductory scenarios discussed, the Azure Service Bus customer library offers back up for additional scenarios to aid take reward of the full feature fix of the Azure Service Autobus service. In order to assist explore some of these scenarios, the Service Coach client library offers a project of samples to serve as an illustration for common scenarios. Please meet the samples README for details.

Contributing

This project welcomes contributions and suggestions. Most contributions require y'all to hold to a Contributor License Agreement (CLA) declaring that yous have the right to, and really do, grant u.s.a. the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically make up one's mind whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided past the bot. You lot will merely need to do this once across all repos using our CLA.

This projection has adopted the Microsoft Open Source Lawmaking of Conduct. For more than information see the Code of Carry FAQ or contact opencode@microsoft.com with any additional questions or comments.

Please see our contributing guide for more information.

Impressions

berrysurew1948.blogspot.com

Source: https://docs.microsoft.com/en-us/dotnet/api/overview/azure/messaging.servicebus-readme-pre

Posting Komentar untuk "Add to Queue Share Dead Again"