Как мне вызвать API из сервисной шины - PullRequest
0 голосов
/ 04 июля 2018

Я пытаюсь научиться создавать приложение на основе микросервисов, где микросервисы могли бы связываться через служебную шину. В моем случае я использую служебную шину Azure.

При ссылке на ссылку ниже устанавливается начальная система. Сообщения достигают очереди.

https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-multi-tier-app-using-service-bus-queues

Но в качестве следующего шага или имитации реального приложения у меня есть OrderAPI для обработки заказов.

Вот так выглядит мой класс WorkerRole

namespace OrderProcessingRole
{
 public class WorkerRole : RoleEntryPoint
 {
    // The name of your queue
    const string QueueName = "ProcessingQueue";

    // QueueClient is thread-safe. Recommended that you cache 
    // rather than recreating it on every request
    QueueClient Client;
    ManualResetEvent CompletedEvent = new ManualResetEvent(false);

    public override void Run()
    {
        Trace.WriteLine("Starting processing of messages");

        // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.
        Client.OnMessage((receivedMessage) =>
            {
                try
                {
                    // Process the message
                    Trace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());
                }
                catch
                {
                    // Handle any message processing specific exceptions here
                }
            });

        CompletedEvent.WaitOne();
     }

     public override bool OnStart()
     {
        // Set the maximum number of concurrent connections 
        ServicePointManager.DefaultConnectionLimit = 12;

        // Create the queue if it does not exist already
        string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
        var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
        if (!namespaceManager.QueueExists(QueueName))
        {
            namespaceManager.CreateQueue(QueueName);
        }

        // Initialize the connection to Service Bus Queue
        Client = QueueClient.CreateFromConnectionString(connectionString, QueueName);
        return base.OnStart();
    }

    public override void OnStop()
    {
        // Close the connection to Service Bus Queue
        Client.Close();
        CompletedEvent.Set();
        base.OnStop();
    }}}

Я не уверен, как и где мне позвонить в OrdersAPI, когда служебная шина установлена.

Я предполагаю, что это будет в

OnStart() -> 
Client.OnMessage((receivedMessage) =>
            {
                try
                {
                   //Order API call here
                }
                catch
                {

                }
            });

Если мои предположения верны, то как я называю свой OrderAPI, размещенный на

http://localhost:8090/api/order

Спасибо.

Ответы [ 2 ]

0 голосов
/ 10 июля 2018

API заказов должен вызываться внутри

Run() -> 
Client.OnMessage((receivedMessage) =>
            {
                try
                {
                   //Order API call here
                }
                catch
                {

                }
            });

Используйте HttpClient для запуска API. При этом API будет вызываться при получении сообщения из очереди.

Поскольку рабочая роль размещается в среде Azure, API-интерфейсы, размещенные в общедоступных местах, могут вызываться только отсюда. Он не идентифицирует API, размещенный на локальной машине. Попробуйте разместить API в Служба приложений Azure или Приложение функций Azure .

0 голосов
/ 04 июля 2018

Предполагая, что OrdersAPI - это ваша конечная точка Web API, получающая запросы от браузера, она будет создавать сообщения Azure Service Bus и отправлять в очередь. Ваша рабочая роль получит эти сообщения и обработает их. Обработка не будет выполняться в Web API.

...