Azure Service Bus Brokered Message泵,等待多种消息类型

时间:2017-09-04 04:56:58

标签: generics azureservicebus

我的消息泵看起来像这样:

public class MessagePump<T> where T : class
    {
        public async Task Run( string inQueue, IMessageProcessor<T> processor, CancellationToken cancellationToken)
        {
            var connectionString = Settings.ServiceBusConnectionString;
            var factory = MessagingFactory.CreateFromConnectionString(connectionString);
            var client = factory.CreateQueueClient(inQueue);
            var msgOptions = new OnMessageOptions
            {
                AutoComplete = false,
                MaxConcurrentCalls = 5,
                AutoRenewTimeout = TimeSpan.FromMinutes(10)
            };
            await Task.Run(() =>
            client.OnMessageAsync(
              async message =>
              {
                  await OnReceived(message, processor);
                  await message.CompleteAsync();
              }, msgOptions),
              cancellationToken);
        }
        static async Task OnReceived(BrokeredMessage brokeredMessage, IMessageProcessor<T> processor)
        {
            var message = brokeredMessage.GetBody<T>();
            try
            {
                await processor.Process(message);
            }
            catch (Exception e)
            {
                var er = new ErrorLog();
                await er.Create(new {error = e.Message});
            }

        }
    }

从Azure Service Fabric

中的无状态服务调用它
internal sealed class Core : StatelessService
    {
        public Core(StatelessServiceContext context)
            : base(context)
        { }


        protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            return new ServiceInstanceListener[0];
        }

        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            var inQueue = Settings.CoreQueue;
            await new MessagePump<Message>().Run(inQueue, new Processor(), cancellationToken);

        }
    }

如何创建处理多种消息类型的消息泵?

1 个答案:

答案 0 :(得分:2)

有几个选择:

  1. 将所有类型编码为一种容器类型的一部分(例如,从一个基类派生所有类型,或将它们全部放入容器类型的属性中)。始终反序列化此容器,然后根据其内容处理它。

  2. 将邮件类型放入元数据(例如LPRPhotoCaptureCameraDelegate.h LPRPhotoCaptureCamera.h属性。阅读此元数据后反序列化为特定类型。

  3. 调用只返回字节数组的ContentType,并自行处理反序列化。如果您不控制发送方,可能是唯一的选择。