public void Publish(IntegrationEvent @event) { if (!_persistentConnection.IsConnected) { _persistentConnection.TryConnect(); } using (var channel = _persistentConnection.CreateModel()) { var eventName = @event.GetType() .Name; channel.ExchangeDeclare(exchange: BrokerName, type: "direct"); var message = JsonConvert.SerializeObject(@event); var body = Encoding.UTF8.GetBytes(message); var properties = channel.CreateBasicProperties(); properties.DeliveryMode = 2; // persistent channel.BasicPublish(exchange: BrokerName, routingKey: eventName, mandatory: true, basicProperties: properties, body: body); } }
void EnsureRabbitConnectionExists(IServiceCollection services) { var factory = new ConnectionFactory() { HostName = Configuration["EventBusConnection"] }; if (!string.IsNullOrEmpty(Configuration["EventBusUserName"])) { factory.UserName = Configuration["EventBusUserName"]; } if (!string.IsNullOrEmpty(Configuration["EventBusPassword"])) { factory.Password = Configuration["EventBusPassword"]; } var retryCount = 5; var scopeFactory = services .BuildServiceProvider() .GetRequiredService <IServiceScopeFactory>(); using (var scope = scopeFactory.CreateScope()) { var provider = scope.ServiceProvider; var logger = provider.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >(); using (var persistentConnection = new DefaultRabbitMQPersistentConnection(factory, logger, retryCount)) { persistentConnection.TryConnect(); } } }
/// <summary> /// 添加RabbitMQEventBus /// </summary> /// <param name="services"></param> /// <param name="connectionAction">使用匿名函数取得连接字符串,用来兼容使用Consul获取服务地址的情况</param> /// <param name="eventBusOptionAction"></param> /// <returns></returns> public static IServiceCollection AddRabbitMQEventBus(this IServiceCollection services, Func <string> connectionAction, Action <RabbitMQEventBusConnectionConfigurationBuild> eventBusOptionAction) { RabbitMQEventBusConnectionConfiguration configuration = new RabbitMQEventBusConnectionConfiguration(); RabbitMQEventBusConnectionConfigurationBuild configurationBuild = new RabbitMQEventBusConnectionConfigurationBuild(configuration); eventBusOptionAction?.Invoke(configurationBuild); services.TryAddSingleton <IRabbitMQPersistentConnection>(options => { ILogger <DefaultRabbitMQPersistentConnection> logger = options.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >(); var connection = new DefaultRabbitMQPersistentConnection(configuration, connectionAction, logger); connection.TryConnect(); return(connection); }); services.TryAddSingleton <IEventHandlerModuleFactory, EventHandlerModuleFactory>(); services.TryAddSingleton <IRabbitMQEventBus, DefaultRabbitMQEventBus>(); foreach (Type mType in typeof(IEvent).GetAssemblies()) { services.TryAddTransient(mType); foreach (Type hType in typeof(IEventHandler <>).GetMakeGenericType(mType)) { services.TryAddTransient(hType); } } return(services); }
protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); var loggerFactory = (ILoggerFactory) new LoggerFactory(); var loggerConnection = loggerFactory.CreateLogger <DefaultRabbitMQPersistentConnection>(); var factory = new ConnectionFactory() { HostName = "localhost", DispatchConsumersAsync = true, UserName = "******", Password = "******" }; DefaultRabbitMQPersistentConnection rabbitmqConnection = new DefaultRabbitMQPersistentConnection(factory, loggerConnection, 5); if (!rabbitmqConnection.IsConnected) { rabbitmqConnection.TryConnect(); } var logger = loggerFactory.CreateLogger <EventBusRabbitMQ>(); //DI var builder = new ContainerBuilder(); builder.RegisterType <DispatchAcceptEventHandler>().InstancePerLifetimeScope(); var eventBus = new EventBusRabbitMQ(rabbitmqConnection, logger, builder.Build(), 5); //Subscribes eventBus.Subscribe <DispatchAcceptEvent, DispatchAcceptEventHandler>(); }
public void Dispose_ConnectionDisposeThrowsIOException_LogCritical( [Frozen] Mock <ILogger <DefaultRabbitMQPersistentConnection> > mockLogger, [Frozen] Mock <IConnectionFactory> mockConnectionFactory, [Frozen] Mock <IConnection> mockConnection, DefaultRabbitMQPersistentConnection sut ) { //Arrange mockConnection.Setup(_ => _.IsOpen) .Returns(true); mockConnection.Setup(_ => _.Dispose()) .Throws <IOException>(); mockConnectionFactory.Setup(_ => _.CreateConnection()) .Returns(mockConnection.Object); //Act sut.TryConnect(); sut.Dispose(); //Assert mockLogger.Verify( _ => _.Log( It.Is <LogLevel>(logLevel => logLevel == LogLevel.Critical), It.Is <EventId>(eventId => eventId.Id == 0), It.IsAny <It.IsAnyType>(), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>() ), Times.Once ); }
/// <summary> /// 添加RabbitMQEventBus /// </summary> /// <param name="services"></param> /// <param name="connectionString"></param> /// <param name="eventBusOptionAction"></param> /// <returns></returns> public static IServiceCollection AddRabbitMQEventBus(this IServiceCollection services, string connectionString, Action <RabbitMQEventBusConnectionConfigurationBuild> eventBusOptionAction) { RabbitMQEventBusConnectionConfiguration configuration = new RabbitMQEventBusConnectionConfiguration(); RabbitMQEventBusConnectionConfigurationBuild configurationBuild = new RabbitMQEventBusConnectionConfigurationBuild(configuration); eventBusOptionAction?.Invoke(configurationBuild); services.TryAddSingleton <IRabbitMQPersistentConnection>(options => { ILogger <DefaultRabbitMQPersistentConnection> logger = options.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >(); IConnectionFactory factory = new ConnectionFactory { AutomaticRecoveryEnabled = configuration.AutomaticRecoveryEnabled, NetworkRecoveryInterval = configuration.NetworkRecoveryInterval, Uri = new Uri(connectionString), }; var connection = new DefaultRabbitMQPersistentConnection(configuration, factory, logger); connection.TryConnect(); return(connection); }); services.TryAddSingleton <IEventHandlerModuleFactory, EventHandlerModuleFactory>(); services.TryAddSingleton <IRabbitMQEventBus, DefaultRabbitMQEventBus>(); foreach (Type mType in typeof(IEvent).GetAssemblies()) { services.TryAddTransient(mType); foreach (Type hType in typeof(IEventHandler <>).GetMakeGenericType(mType)) { services.TryAddTransient(hType); } } return(services); }
public void EventBusRabbitMQProducer_Publish_Success() { OrderCreateEvent eventMessage = new OrderCreateEvent(); eventMessage.AuctionId = "dummy1"; eventMessage.ProductId = "dummy_product_1"; eventMessage.Price = 10; eventMessage.Quantity = 100; eventMessage.SellerUserName = "******"; var factory = new ConnectionFactory() { HostName = "localhost" }; factory.UserName = "******"; factory.Password = "******"; _defaultRabbitMQPersistentConnection.TryConnect(); //_eventBusRabbitMQProducer.Publish("orderCreateQueue", eventMessage); }
public void TryConnect() { Mock <ILogger <DefaultRabbitMQPersistentConnection> > logger = new Mock <ILogger <DefaultRabbitMQPersistentConnection> >(); using (DefaultRabbitMQPersistentConnection con = new DefaultRabbitMQPersistentConnection(_rabbitMqConnection, logger.Object)) { var result = con.TryConnect(); Assert.IsTrue(result); } }
public void TryConnect_ConnectionFactoryNull_ReturnFalse() { IConnection connection = null; _mockIConnectionFactory.Setup(c => c.CreateConnection()).Returns(connection); var result = _defaultRabbitMQPersistentConnection.TryConnect(); Assert.False(result); }
public void RabbitMQConnection_TryConnect_Success() { var factory = new ConnectionFactory() { HostName = "localhost" }; factory.UserName = "******"; factory.Password = "******"; _defaultRabbitMQPersistentConnection = new DefaultRabbitMQPersistentConnection(factory, 5, _mockLogger.Object); var result = _defaultRabbitMQPersistentConnection.TryConnect(); Assert.True(result); }
public void CreateModel_ConnectionIsOpen_ReturnsModel( [Frozen] Mock <IConnectionFactory> mockConnectionFactory, [Frozen] Mock <IConnection> mockConnection, DefaultRabbitMQPersistentConnection sut ) { //Arrange mockConnection.Setup(_ => _.IsOpen) .Returns(true); mockConnectionFactory.Setup(_ => _.CreateConnection()) .Returns(mockConnection.Object); //Act sut.TryConnect(); var result = sut.CreateModel(); //Assert result.Should().NotBeNull(); }
public void IsConnected_ConnectionIsDisposed_ReturnsFalse( [Frozen] Mock <IConnectionFactory> mockConnectionFactory, [Frozen] Mock <IConnection> mockConnection, DefaultRabbitMQPersistentConnection sut ) { //Arrange mockConnection.Setup(_ => _.IsOpen) .Returns(true); mockConnectionFactory.Setup(_ => _.CreateConnection()) .Returns(mockConnection.Object); //Act sut.TryConnect(); sut.Dispose(); //Assert mockConnection.Verify(_ => _.Dispose()); }
public void Test1() { var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); }); ILogger <DefaultRabbitMQPersistentConnection> logger = loggerFactory.CreateLogger <DefaultRabbitMQPersistentConnection>(); IConnectionFactory connectionFactory = new ConnectionFactory() { HostName = "localhost" }; IRabbitMQPersistentConnection rabbitMqPersistentConnection = new DefaultRabbitMQPersistentConnection(connectionFactory, logger); rabbitMqPersistentConnection.TryConnect(); var isconnect = rabbitMqPersistentConnection.IsConnected; using (var channel = rabbitMqPersistentConnection.CreateModel()) { channel.ExchangeDeclare(exchange: "testEX5", type: "direct"); channel.QueueDeclare(queue: "testQueue5", durable: true, exclusive: false, autoDelete: false, arguments: null); string message = "Hello World!"; var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "testEX5", routingKey: "testEX5", basicProperties: null, body: body); } }
public void EventBusOrderCreateConsumer_Publish_Success() { var factory = new ConnectionFactory() { HostName = "localhost" }; factory.UserName = "******"; factory.Password = "******"; var _defaultRabbitMQPersistentConnection = new DefaultRabbitMQPersistentConnection(factory, 5, _mockLogger.Object); _mockPersistentConnection.Setup(p => p.TryConnect()).Returns(_defaultRabbitMQPersistentConnection.TryConnect()); //_defaultRabbitMQPersistentConnection.TryConnect(); //_eventBusOrderCreateConsumer.Consume(); }
public void Dispose_ConnectionIsNotNull_NoLog( [Frozen] Mock <ILogger <DefaultRabbitMQPersistentConnection> > mockLogger, DefaultRabbitMQPersistentConnection sut ) { //Arrange //Act sut.TryConnect(); sut.Dispose(); //Assert mockLogger.Verify( _ => _.Log( It.Is <LogLevel>(logLevel => logLevel == LogLevel.Error), It.Is <EventId>(eventId => eventId.Id == 0), It.IsAny <It.IsAnyType>(), It.IsAny <Exception>(), It.IsAny <Func <It.IsAnyType, Exception, string> >() ), Times.Never ); }
public static IHummingbirdEventBusHostBuilder AddRabbitmq(this IHummingbirdEventBusHostBuilder hostBuilder, Action <RabbitMqOption> setupConnectionFactory) { setupConnectionFactory = setupConnectionFactory ?? throw new ArgumentNullException(nameof(setupConnectionFactory)); var option = new RabbitMqOption(); setupConnectionFactory(option); hostBuilder.Services.AddSingleton <IConnectionFactory>(sp => { var logger = sp.GetRequiredService <ILogger <IConnectionFactory> >(); var factory = new ConnectionFactory(); factory.Port = option.Port; factory.Password = option.Password; factory.UserName = option.UserName; factory.VirtualHost = option.VirtualHost; factory.AutomaticRecoveryEnabled = true; factory.TopologyRecoveryEnabled = true; factory.UseBackgroundThreadsForIO = true; return(factory); }); hostBuilder.Services.AddSingleton <ILoadBalancerFactory <IRabbitMQPersistentConnection> >(sp => { return(new DefaultLoadBalancerFactory <IRabbitMQPersistentConnection>()); }); hostBuilder.Services.AddSingleton <IEventBus, EventBusRabbitMQ>(sp => { var logger = sp.GetRequiredService <ILogger <IEventBus> >(); var loggerConnection = sp.GetRequiredService <ILogger <IRabbitMQPersistentConnection> >(); var rabbitMQPersisterConnectionLoadBalancerFactory = sp.GetRequiredService <ILoadBalancerFactory <IRabbitMQPersistentConnection> >(); var connectionFactory = sp.GetRequiredService <IConnectionFactory>(); var senderConnections = new List <IRabbitMQPersistentConnection>(); var receiveConnections = new List <IRabbitMQPersistentConnection>(); var hosts = option.HostName.Split(',').ToList(); //消费端连接池 for (int i = 0; i < option.ReceiverMaxConnections; i++) { var connection = new DefaultRabbitMQPersistentConnection(hosts, connectionFactory, loggerConnection, option.ReceiverAcquireRetryAttempts); connection.TryConnect(); //消费端的连接池 receiveConnections.Add(connection); } //发送端连接池 for (int i = 0; i < option.SenderMaxConnections; i++) { var connection = new DefaultRabbitMQPersistentConnection(hosts, connectionFactory, loggerConnection, option.SenderAcquireRetryAttempts); connection.TryConnect(); senderConnections.Add(connection); } var receiveLoadBlancer = rabbitMQPersisterConnectionLoadBalancerFactory.Get(() => receiveConnections, option.ReceiverLoadBalancer); var senderLoadBlancer = rabbitMQPersisterConnectionLoadBalancerFactory.Get(() => senderConnections, option.SenderLoadBalancer); return(new EventBusRabbitMQ( receiveLoadBlancer, senderLoadBlancer, logger, sp, senderRetryCount: option.SenderAcquireRetryAttempts, senderConfirmTimeoutMillseconds: option.SenderConfirmTimeoutMillseconds, reveiverMaxDegreeOfParallelism: option.ReveiverMaxDegreeOfParallelism, receiverAcquireRetryAttempts: option.ReceiverAcquireRetryAttempts, receiverHandlerTimeoutMillseconds: option.ReceiverHandlerTimeoutMillseconds, preFetch: option.PreFetch, exchange: option.Exchange, exchangeType: option.ExchangeType )); }); return(hostBuilder); }