简体   繁体   中英

Publish/subscribe with Azure Service Bus

I have a Microservice (Web API), that publish messages to a Topic (Topic A).

Now I have another Microservice (Web API) that should subscribe to this topic and act upon the messages.

My question is simply: How should I do this since my Microservice that should subscribe to the Topic is a WebApi? In my web api, I want in somehow instantly know when a new message is available in the Topic. Should I poll the service bus via an endpoint?

I'm uncertain about the best practices about this.

All examples that I have seen using console applications to subscribe. But that's not my case since I have an web api.

There are different ways of doing this.

1. Using Azure Functions

This way you create two applications. Your standard web api, and separately you create an Azure Function that will handle the messages from the queue. There multiple benefits of this approach, on of them is that you are isolating the code handling the queue, so if you have many messages, it will not affect the performance of your API

2. Using a Singleton service inside your web application

The idea here is that your API application is handling queue messages in the background. This has the advantage that you have only one application doing everything, simpler to maintain for example. It has the disadvantage that a very big inflow of messages will slow down your APIs.

(Note, in the link above look for Consuming messaging from the Queue

Whether is a WebAPI or a console , it is the responsibility of the consumer to communicates and collect records. Being a WebAPI doesn't mean that it should only have public endpoints. Typical WebAPI, might have public endpoint (for external world) or can have private endpoints (for internal communications) or can have a combination of both. The responsibility of private endpoints could be reading data from service data-store, consuming external services via adapter services etc. In your case, upon initialization of your WebAPI, you might want to create a consumer object and start reading data and process as you want. Hope this help.

You can poll in a Web Job or background task. But the built-in way to do this is with an Azure Function triggered from the Topic, or with Azure Event Grid .

For listening in the background you can use IHostedService . Inside Method StartAsync

you can register message processors;

  queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions)

And on StopAsync you can stop processing messages and close the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM