消息队列

优质
小牛编辑
144浏览
2023-12-01

rabbitmq 使用

定义handler实体

 public class UserEvent : EventHandler
 {
     public string Name { get; set; }
     public string Job { get; set; }
 }

队列定义

[QueueConsumer(nameof(HelloEventHandler), QueueConsumerMode.Normal, QueueConsumerMode.Retry, QueueConsumerMode.Fail)]
QueueConsumerMode.Normal:一般队列
QueueConsumerMode.Retry:重试队列
QueueConsumerMode.Fail:死信队列

重写Handle与Handled实现一般队列与重试队列

public override Task Handle(UserEvent @event)
public override Task Handled(EventContext context)

重写FailHandler方法实现死信队列实现

public override Task FailHandler(EventContext context)

发送消息:

 ServiceLocator.GetService<IEventBus>().Publish(new UserEvent()
    {
        Name = "simple",
        Job = "it"
    })

配置:

   "RabbitMQ": {
       "Host": "192.168.190.4",//rabbitmq 地址
       "UserName": "admin",//用户名
       "Password": "qwe123QWE",//密码
       "RetryCount": 3,//重试执行次数
       "FailCount": 1//失败执行次数
   }

例如:

[QueueConsumer(nameof(HelloEventHandler), QueueConsumerMode.Normal, QueueConsumerMode.Retry, QueueConsumerMode.Fail)]
public class HelloEventHandler : BaseEventHandler<UserEvent>
{
    public override Task Handle(UserEvent @event)
    {

        Console.WriteLine($"消费。{@event.Name}---{@event.Job}");
        throw new Exception();
    }

    public override Task Handled(EventContext context)
    {
        Console.WriteLine($"调用{context.Count}次。类型:{context.Type}");
        var model = context.Content as UserEvent;
        return Task.CompletedTask;
    }

    //失败消息处理
    public override Task FailHandler(EventContext context)
    {
        Console.WriteLine($"调用{context.Count}次。私信队列方法 ,方法,类型:{context.Type}");
        return base.FailHandler(context);
    }
}