RabbitMQ.Bus

本文介绍了一个基于ASP.NET Core的RabbitMQ封装库,使用RabbitMQ.Client实现,并通过Autofac进行依赖注入管理。支持Topic模式,详细展示了配置、订阅处理及发送消息的方法。

一个.netcore下的,十分简单的rabbitmq封装,基于RabbitMQ.Client

 Nuget

https://www.nuget.org/packages/RabbitMQ.Bus/

https://www.nuget.org/packages/RabbitMQ.Bus.Autofac/Git

 

采用autofac进行DI的管理
目前仅支持Topic模式

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    var AssemblyName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
    services.AddMvc();
    services.AddRabbitMQBus("amqp://guest:guest@192.168.0.252:5672/");
    //OR
    services.AddRabbitMQBus("amqp://guest:guest@192.168.0.252:5672/", options =>
    {
        //添加客户端可读名称
        options.ClientProvidedName = AssemblyName;
        //关闭网络自动恢复
        options.AutomaticRecoveryEnabled = false;
        //关闭持久化消息
        options.Persistence = false;
        //无消费者时消息重新发送的间隔时间
        options.NoConsumerMessageRetryInterval = TimeSpan.FromSeconds(3);
        //开启Autofac支持
        //options.AddAutofac(services);
        //开启Autofac支持并开启butterfly支持
        options.AddAutofac(services, butterfly =>
        {
            butterfly.CollectorUrl = "http://192.168.0.252:9618";
            butterfly.Service = AssemblyName;
        });
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   //true为自动订阅,默认false,则采用之前的订阅方式,注入RabbitMQBusService后使用Subscribe泛型进行订阅
   app.UseRabbitMQBus(true);
}

 

使用方法

在asp.net core中

 

 订阅处理方法

 

[Queue(ExchangeName = "dev.ex", RoutingKey = "send.#")]
public class Person
{
    public string Name { set; get; }
}
public class PersonHandler : IRabbitMQBusHandler<Person>
{
    public Task Handle(Person message)
    {
        Console.WriteLine($"收到消息:{message.Name}");
        return Task.CompletedTask;
    }
}

 

发送消息
[Route("api/v1/[controller]")]
public class IndexController : Controller
{
   private readonly IRabbitMQBus _rabbit;
   public IndexController(IRabbitMQBus rabbit)
   {
      _rabbit = rabbit ?? throw new ArgumentNullException(nameof(rabbit));
   }
   [HttpPost]
   public async Task<IActionResult> Send()
   {
      _rabbit.Publish( new { Name = "Hello RabbitMQ" }, routingKey: "send.message",exchangeName: "dev.ex");
      //OR
      _rabbit.Publish(new Person{ Name = "Hello RabbitMQ" });
   }
}

 

转载于:https://www.cnblogs.com/luacloud/p/9365875.html

---> System.AggregateException: One or more errors occurred. (Connection failed) ---> RabbitMQ.Client.Exceptions.ConnectFailureException: Connection failed ---> System.ArgumentException: IPv4 address 0.0.0.0 and IPv6 address ::0 are unspecified addresses that cannot be used as a target address. (Parameter 'hostName') at System.Net.Dns.HostResolutionBeginHelper(String hostName, Boolean justReturnParsedIp, Boolean throwOnIIPAny, AsyncCallback requestCallback, Object state) at System.Net.Dns.BeginGetHostAddresses(String hostNameOrAddress, AsyncCallback requestCallback, Object state) at System.Net.Dns.<>c.<GetHostAddressesAsync>b__25_0(String arg, AsyncCallback requestCallback, Object stateObject) at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1](Func`4 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory`1.FromAsync[TArg1](Func`4 beginMethod, Func`2 endMethod, TArg1 arg1, Object state) at System.Net.Dns.GetHostAddressesAsync(String hostNameOrAddress) at RabbitMQ.Client.Impl.TcpClientAdapter.ConnectAsync(String host, Int32 port) at RabbitMQ.Client.Impl.TaskExtensions.TimeoutAfter(Task task, TimeSpan timeout) at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, TimeSpan timeout) --- End of inner exception stack trace --- at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingAddressFamily(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan timeout, AddressFamily family) at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingIPv4(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan timeout) at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout) at RabbitMQ.Client.Framing.Impl.IProtocolExtensions.CreateFrameHandler(IProtocol protocol, AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout) at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint) at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector) --- End of inner exception stack trace --- at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector) at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName) --- End of inner exception stack trace --- at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName) at RabbitMQ.Client.ConnectionFactory.CreateConnection(String clientProvidedName) at EasyNetQ.ConnectionFactoryWrapper.CreateConnection() at EasyNetQ.PersistentConnection.TryToConnect() 2025-12-08 11:06:14.0108||ERROR|EasyNetQ.PersistentConnection|Failed to connect to any Broker. Retrying in 00:00:05 2025-12-08 11:06:19.0140||DEBUG|EasyNetQ.PersistentConnection|Trying to connect 2025-12-08 11:06:19.0190||ERROR|EasyNetQ.PersistentConnection|Failed to connect to broker "0.0.0.0", port 5672, vhost "/" RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable ---> System.AggregateException: One or more errors occurred. (Connection failed) ---> RabbitMQ.Client.Exceptions.ConnectFailureException: Connection failed ---> System.ArgumentException: IPv4 address 0.0.0.0 and IPv6 address ::0 are unspecified addresses that cannot be used as a target address. (Parameter 'hostName') at System.Net.Dns.HostResolutionBeginHelper(String hostName, Boolean justReturnParsedIp, Boolean throwOnIIPAny, AsyncCallback requestCallback, Object state) at System.Net.Dns.BeginGetHostAddresses(String hostNameOrAddress, AsyncCallback requestCallback, Object state) at System.Net.Dns.<>c.<GetHostAddressesAsync>b__25_0(String arg, AsyncCallback requestCallback, Object stateObject) at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1](Func`4 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory`1.FromAsync[TArg1](Func`4 beginMethod, Func`2 endMethod, TArg1 arg1, Object state) at System.Net.Dns.GetHostAddressesAsync(String hostNameOrAddress) at RabbitMQ.Client.Impl.TcpClientAdapter.ConnectAsync(String host, Int32 port) at RabbitMQ.Client.Impl.TaskExtensions.TimeoutAfter(Task task, TimeSpan timeout) at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, TimeSpan timeout) --- End of inner exception stack trace --- at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingAddressFamily(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan timeout, AddressFamily family) at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingIPv4(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan timeout) at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout) at RabbitMQ.Client.Framing.Impl.IProtocolExtensions.CreateFrameHandler(IProtocol protocol, AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout) at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint) at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector) --- End of inner exception stack trace --- at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector) at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName) --- End of inner exception stack trace --- at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName) at RabbitMQ.Client.ConnectionFactory.CreateConnection(String clientProvidedName) at EasyNetQ.ConnectionFactoryWrapper.CreateConnection() at EasyNetQ.PersistentConnection.TryToConnect() 2025-12-08 11:06:19.0243||ERROR|EasyNetQ.PersistentConnection|Failed to connect to any Broker. Retrying in 00:00:05 2025-12-08 11:06:20.3625||ERROR|EasyNetQ.Producer.PersistentChannel|Channel action timed out 2025-12-08 11:06:32.0563||INFO|AntiUAV.DeviceServer.Program|loaded plugin for resource AntiUAV.DevicePlugin.Obstruct14.dll. 2025-12-08 11:06:33.6995||INFO|AntiUAV.DeviceServer.Serrvice.ServiceOpt|device server initialization finished. (devId:20,devCategory:30203) 2025-12-08 11:06:33.7285||INFO|AntiUAV.DevicePlugin.Obstruct14.DeviceHostService|devServ udp listion start.(devId:20,ip:127.0.0.1,port:9991) 2025-12-08 11:06:33.8567||DEBUG|EasyNetQ.PersistentConnection|Trying to connect 2025-12-08 11:06:33.8720||ERROR|EasyNetQ.PersistentConnection|Failed to connect to broker "0.0.0.0", port 5672, vhost "/" RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable ---> System.AggregateException: One or more errors occurred. (Connection failed) ---> RabbitMQ.Client.Exceptions.ConnectFailureException: Connection failed ---> System.ArgumentException: IPv4 address 0.0.0.0 and IPv6 address ::0 are unspecified addresses that cannot be used as a target address. (Parameter 'hostName') at System.Net.Dns.HostResolutionBeginHelper(String hostName, Boolean justReturnParsedIp, Boolean throwOnIIPAny, AsyncCallback requestCallback, Object state) at System.Net.Dns.BeginGetHostAddresses(String hostNameOrAddress, AsyncCallback requestCallback, Object state) at System.Net.Dns.<>c.<GetHostAddressesAsync>b__25_0(String arg, AsyncCallback requestCallback, Object stateObject) at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1](Func`4 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory`1.FromAsync[TArg1](Func`4 beginMethod, Func`2 endMethod, TArg1 arg1, Object state) at System.Net.Dns.GetHostAddressesAsync(String hostNameOrAddress) at RabbitMQ.Client.Impl.TcpClientAdapter.ConnectAsync(String host, Int32 port) at RabbitMQ.Client.Impl.TaskExtensions.TimeoutAfter(Task task, TimeSpan timeout) at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, TimeSpan timeout) --- End of inner exception stack trace --- at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingAddressFamily(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan timeout, AddressFamily family) at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingIPv4(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan timeout) at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout) at RabbitMQ.Client.Framing.Impl.IProtocolExtensions.CreateFrameHandler(IProtocol protocol, AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout) at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint) at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector) --- End of inner exception stack trace --- at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector) at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName) --- End of inner exception stack trace --- at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName) at RabbitMQ.Client.ConnectionFactory.CreateConnection(String clientProvidedName) at EasyNetQ.ConnectionFactoryWrapper.CreateConnection() at EasyNetQ.PersistentConnection.TryToConnect() 2025-12-08 11:06:33.9020||ERROR|EasyNetQ.PersistentConnection|Failed to connect to any Broker. Retrying in 00:00:05
最新发布
12-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值