.Net Core 中接受ServiceBus跟QueueClient 消息后端代码

Startup类方法:

  public Startup(IConfiguration configuration)
   { 

            IotController.RegisterMessageHandler();
            IotController.MainAsync();

 }

 

IotController类:

using ByPass.DataModels;
using ByPass.Helpers;
using ByPass.Models;
using ByPassCore.AuthS;
using ByPassCore.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.ServiceBus;
using Newtonsoft.Json;
using reAdmin.Helpers;
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ByPassCore.Controllers
{
  public class IotController : Controller
    {
       //方法一:只使用ExceptionReceivedEventArgs事件

        public static async Task RegisterMessageHandler()
        {
            #region subsIotOutput连接ServiceBus字符串
          
            IotService cfg = IotCfg.Cfg();

            ServiceBusConnectionStringBuilder sb = new ServiceBusConnectionStringBuilder(cfg.subsIotOutput);
            QueueClient queueClient = new QueueClient(sb);

            queueClient.RegisterMessageHandler(
            async (message, token) =>
            {

                var msgStr = Encoding.UTF8.GetString(message.Body);
                var msg = JsonConvert.DeserializeObject<MsgModel>(msgStr);

                if (msg.reserved == "workflowA")
                {
                    switch (msg.code)
                    {
                        case "300":
                         break;

                        default:
                          
                            break;
                    }
                }
                

                await queueClient.CompleteAsync(message.SystemProperties.LockToken);
            },
            (exception) =>
            {
                LogHelper.SaveLog("IotService", exception.Exception + " 439行");
                LogHelper.SaveLog(exception.Exception);
                return Task.CompletedTask;
            });


         

//方法二:

        #region 使用messageHandlerOptions跟ExceptionReceivedEventArgs事件

        private static readonly IotService cfg = IotCfg.Cfg();
        private static readonly ServiceBusConnectionStringBuilder sb = new ServiceBusConnectionStringBuilder(cfg.subsIotOutput);
        private static QueueClient queueClient;

        private static readonly ServiceBusConnectionStringBuilder sbOther = new ServiceBusConnectionStringBuilder(cfg.subsIotOutputStateCode);
        private static QueueClient queueClientOther;
        public static async Task MainAsync()
        {

            queueClient = new QueueClient(sb);
             RegisterOnMessageHandlerAndReceiveMessages();
             await queueClient.CloseAsync();

     }

        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            LogHelper.SaveLog("IotService", "RegisterOnMessageHandlerAndReceiveMessages   Start ");
            // Configure the MessageHandler Options in terms of exception handling, number of concurrent messages to deliver etc.
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                // Maximum number of Concurrent calls to the callback `ProcessMessagesAsync`, set to 1 for simplicity.
                // Set it according to how many messages the application wants to process in parallel.
                MaxConcurrentCalls = 1000,

                // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
                // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
                AutoComplete = false
            };
            LogHelper.SaveLog("IotService", "RegisterOnMessageHandlerAndReceiveMessages   Start 1");
            queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }

        // Complete the message so that it is not received again.
        // This can be done only if the queueClient is created in ReceiveMode.PeekLock mode (which is default).
        // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
        // If queueClient has already been Closed, you may chose to not call CompleteAsync() or AbandonAsync() etc. calls 
        // to avoid unnecessary exceptions.
        /// <summary>
        /// 处理接受的消息
        /// </summary>
        /// <param name="message"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        static async Task ProcessMessagesAsync(Microsoft.Azure.ServiceBus.Message message, CancellationToken token)
        {
           //处理消息的代码

            var msgStr = Encoding.UTF8.GetString(message.Body);
            var msg = JsonConvert.DeserializeObject<MsgModel>(msgStr);

                switch (msg.code)
                {
                    case "300":
                    case "301":     
                     }

            LogHelper.SaveLog("IotService", "处理时间: " + (DateTime.Now - startTime).TotalMilliseconds + " messageId:" + msg.messageId + " messageTime:" + msg.messageTime.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss.fff"));

            await queueClient.CompleteAsync(message.SystemProperties.LockToken);
        }


        /// <summary>
        /// 接收到的异常事件参数\
        /// </summary>
        /// <param name="exceptionReceivedEventArgs"></param>
        /// <returns></returns>
        static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            LogHelper.SaveLog("IotService", exceptionReceivedEventArgs.Exception + " 509 行");
            LogHelper.SaveLog(exceptionReceivedEventArgs.Exception);

            return Task.CompletedTask;
        }

}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pandi18

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值