如何在ASP.NET MVC Web应用程序的View.cshtml中从Azure服务总线(队列)获取消息

sgtfey8w  于 2023-01-27  发布在  .NET
关注(0)|答案(1)|浏览(91)

我有一个控制台应用程序,可以使用它从Azure服务总线(队列)获取消息。

using System;
using System.Text;
using System.Text.Json;
using Microsoft.Azure.ServiceBus;
using SampleShared.Models;

namespace SampleAppReceiver
{
    class Program
    {
        const string connString = "<my_connection_string>";
        static IQueueClient qClient;

        static async Task Main(string[] args)
        {
            qClient = new QueueClient(connString, "<my_queue_name>");

            var msgOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                // How many messages we can process at time
                MaxConcurrentCalls = 1,

                // need to wait until a message is fully processed
                AutoComplete = false,
            };

            qClient.RegisterMessageHandler(ProcessMessageAsync, msgOptions);

            Console.ReadLine();
            await qClient.CloseAsync();
        }

        private static async Task ProcessMessageAsync(Message msg, CancellationToken token)
        {
            // Deserialise the msg body
            var jsonBody = Encoding.UTF8.GetString(msg.Body);
            var personObj = JsonSerializer.Deserialize<Person>(jsonBody);

            Console.WriteLine($"Login: {personObj.Login}");
            Console.WriteLine($"Message: {personObj.Message}");

            // Updating the queue that the message has been processed sucsessfully
            await qClient.CompleteAsync(msg.SystemProperties.LockToken);
        }

        private static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs args)
        {
            Console.WriteLine($"Something went wrong, {args.Exception}");
            return Task.CompletedTask;
        }
    }
}

如何正确地将所有接收到的消息从控制器添加到View.cshtml
现在我有了一个服务(C#接口),可以使用它将消息从View.cshtml发送到Azure服务总线(队列):

// ...
public interface IAzureBusService
{
    Task SendMessageAsync(Person personMessage, string queueName);
}
// ...

控制器方法:

[HttpPost]
public async Task<IActionResult> Index(Person person)
{
    await _busService.SendMessageAsync(person, "personqueue");
    return RedirectToAction("Index");
}
s3fp2yjn

s3fp2yjn1#

1.在Azure门户中创建服务总线。

1.按照下面的屏幕截图创建一个队列。

我按照以下步骤在视图中显示队列消息。
您可以使用MVC项目中的控制台应用程序引用,通过调用从队列获取消息的方法,在视图中显示队列消息。
您需要在控制器类中使用以下代码。

public ActionResult Index()
        {
            List<QueueMsgs> queMsglist = new List<QueueMsgs>();

                QueueMsgs msgs   = new QueueMsgs();
                queMsglist = GetMessagesFromQueue();
                return View(queMsglist);
        }
public void GetMessagesFromQueue()
        {
            ServiceBusReceiver receiver = new ServiceBusReceiver();
            receiver.Listener();
        }

public void Listener()
        {
            ServiceBusConnectionStringBuilder conStr;
            QueueClient client;
            try
            {
                conStr = new ServiceBusConnectionStringBuilder(QueueAccessKey);
                client = new QueueClient(conStr, ReceiveMode.ReceiveAndDelete, RetryPolicy.Default);
                var messageHandler = new MessageHandlerOptions(ListenerExceptionHandler)
                {
                    MaxConcurrentCalls = 1,
                    AutoComplete = false

                };
                client.RegisterMessageHandler(ReceiveMessageFromQ, messageHandler);
            }
            catch (Exception exe)
            {
                Console.WriteLine("{0}", exe.Message);
                Console.WriteLine("Please restart application ");
            }

 public async Task ReceiveMessageFromQ(Message message, CancellationToken token)
        {
            string result = Encoding.UTF8.GetString(message.Body);
            Console.WriteLine("Message received from Queue = {0}", result);
            await Task.CompletedTask;
         }

        public Task ListenerExceptionHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine("{0}", exceptionReceivedEventArgs.Exception);
            return Task.CompletedTask;
        }
@model IEnumerable<MVC.Models.QueueMsgs>

@{
    ViewBag.Title = "Queue Messages";
}

@foreach (var item in Model)
{
        <div>
        @item.message
            <hr />
        </div>
}

在视图中显示队列消息。

相关问题