如何在C#控制台应用程序中从事件网格的QueueStorageAzure门户接收消息?

问题描述

我在C#控制台应用程序中使用事件网格来发送存储在Azure门户中QueueStorage帐户中的事件。问题是“如何接收存储在C#控制台应用程序中的消息?例如:

Azure Portal

在图像中,您可以看到创建的主题和存在的订阅。因此,订阅“ queue-sub”已存储了从另一个C#控制台应用程序发送的所有消息。此C#控制台应用程序实现了“ EventBus”的eShopContainer库,并且我正在创建一个库以将“ EventGrid”与“ EventBus”接口一起使用。例如:

public void Subscribe<T,TH>()
        where T : IntegrationEvent
        where TH : IIntegrationEventHandler<T>
    {
        
    }

如果这来自实现接口“ IEventBus”的片段代码,并且该接口告诉我“我需要订阅以监听事件”,但我不知道该怎么做。

如果您检查我正在工作的整个项目,则为git链接。 https://github.com/Angel1803/EventGridListenerMessage.git

解决方法

这是您如何编写代码以使用IEventBus接收消息的方法:

namespace Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.EventHandling
{
    public class ProductPriceChangedIntegrationEventHandler :
        IIntegrationEventHandler<ProductPriceChangedIntegrationEvent>
    {
        private readonly IBasketRepository _repository;

        public ProductPriceChangedIntegrationEventHandler(
            IBasketRepository repository)
        {
            _repository = repository;
        }

        public async Task Handle(ProductPriceChangedIntegrationEvent @event)
        {
            var userIds = await _repository.GetUsers();
            foreach (var id in userIds)
            {
                var basket = await _repository.GetBasket(id);
                await UpdatePriceInBasketItems(@event.ProductId,@event.NewPrice,basket);
            }
        }

        private async Task UpdatePriceInBasketItems(int productId,decimal newPrice,CustomerBasket basket)
        {
            var itemsToUpdate = basket?.Items?.Where(x => int.Parse(x.ProductId) ==
                productId).ToList();
            if (itemsToUpdate != null)
            {
                foreach (var item in itemsToUpdate)
                {
                    if(item.UnitPrice != newPrice)
                    {
                        var originalPrice = item.UnitPrice;
                        item.UnitPrice = newPrice;
                        item.OldUnitPrice = originalPrice;
                    }
                }
                await _repository.UpdateBasket(basket);
            }
        }
    }
}

有关IEventBus使用的完整教程,您可以访问Subscribing to events

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...