/// <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); }
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(); } } }
public DefaultRabbitMQPersistentConnectionTest() { _mockPerConncection = new Mock <IRabbitMQPersistentConnection>(); _mockIConnectionFactory = new Mock <IConnectionFactory>(); _mockLogger = new Mock <ILogger <DefaultRabbitMQPersistentConnection> >(); _defaultRabbitMQPersistentConnection = new DefaultRabbitMQPersistentConnection(_mockIConnectionFactory.Object, 5, _mockLogger.Object); }
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="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); }
public TestEventBus(EventBusOptions options) { _options = options; var eventBusOptions = new OptionsWrapper <EventBusOptions>(options); var logger = new LoggerFactory().CreateLogger <DefaultRabbitMQPersistentConnection>(); _persistentConnection = new DefaultRabbitMQPersistentConnection(logger, eventBusOptions); }
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 CreateModel_ConnectionIsClosed_ThrowsInvalidOperationException( DefaultRabbitMQPersistentConnection sut ) { //Arrange //Act Action act = () => sut.CreateModel(); //Assert act.Should().Throw <InvalidOperationException>(); }
public void IsConnected_ConnectionIsNull_ReturnsFalse( DefaultRabbitMQPersistentConnection sut ) { //Arrange //Act var result = sut.IsConnected; //Assert result.Should().BeFalse(); }
public void ConsumeMessages() { Mock <ILogger <DefaultRabbitMQPersistentConnection> > logger = new Mock <ILogger <DefaultRabbitMQPersistentConnection> >(); Mock <ILogger <Messaging> > logger2 = new Mock <ILogger <Messaging> >(); using (DefaultRabbitMQPersistentConnection con = new DefaultRabbitMQPersistentConnection(_rabbitMqConnection, logger.Object)) { Messaging msg = new Messaging(con, logger2.Object); //msg.PublishMessage(); var result = msg.ConsumeMessages("testQueue", "MessageBusTest"); Assert.AreEqual("new message", result); } }
public EventBusRabbitMQProducerTest() { var factory = new ConnectionFactory() { HostName = "localhost" }; factory.UserName = "******"; factory.Password = "******"; _mockLoggerConn = new Mock <ILogger <DefaultRabbitMQPersistentConnection> >(); _defaultRabbitMQPersistentConnection = new DefaultRabbitMQPersistentConnection(factory, 5, _mockLoggerConn.Object); _mockPersistentConnection = new Mock <IRabbitMQPersistentConnection>(); _mockLogger = new Mock <ILogger <EventBusRabbitMQProducer> >(); _retryCount = 5; _eventBusRabbitMQProducer = new EventBusRabbitMQProducer(_mockPersistentConnection.Object, _mockLogger.Object, _retryCount); }
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 static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration) { var subscriptionClientName = configuration["SubscriptionClientName"]; if (configuration.GetValue <bool>("AzureServiceBusEnabled")) { services.AddSingleton <IEventBus, EventBusServiceBus>(sp => { var serviceBusPersisterConnection = sp.GetRequiredService <IServiceBusPersisterConnection>(); var iLifetimeScope = sp.GetRequiredService <ILifetimeScope>(); var logger = sp.GetRequiredService <ILogger <EventBusServiceBus> >(); var eventBusSubcriptionsManager = sp.GetRequiredService <IEventBusSubscriptionsManager>(); return(new EventBusServiceBus(serviceBusPersisterConnection, logger, eventBusSubcriptionsManager, subscriptionClientName, iLifetimeScope)); }); } else { services.AddSingleton <IEventBus, EventBusRabbitMQ>(sp => { var connectionFactory = sp.GetRequiredService <ConnectionFactory>(); var iLifetimeScope = sp.GetRequiredService <ILifetimeScope>(); var logger = sp.GetRequiredService <ILogger <EventBusRabbitMQ> >(); var eventBusSubcriptionsManager = sp.GetRequiredService <IEventBusSubscriptionsManager>(); var retryCount = 5; // if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"])) // { // retryCount = int.Parse(configuration["EventBusRetryCount"]); // } var rmqlogger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >(); var rabbitMQPersistentConnection = new DefaultRabbitMQPersistentConnection(connectionFactory, rmqlogger, retryCount); return(new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount)); }); } services.AddSingleton <IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>(); services.AddTransient <OrderStatusChangedToAwaitingValidationIntegrationEventHandler>(); services.AddTransient <OrderStatusChangedToPaidIntegrationEventHandler>(); return(services); }
public void PublishMessage() { Mock <ILogger <DefaultRabbitMQPersistentConnection> > logger = new Mock <ILogger <DefaultRabbitMQPersistentConnection> >(); Mock <ILogger <Messaging> > logger2 = new Mock <ILogger <Messaging> >(); using (DefaultRabbitMQPersistentConnection con = new DefaultRabbitMQPersistentConnection(_rabbitMqConnection, logger.Object)) { Messaging msg = new Messaging(con, logger2.Object); MessageBusTest message = new MessageBusTest() { Name = "test" }; var result = msg.PublishMessage(message); Assert.IsTrue(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 Dispose_ConnectionIsNull_NoLog( [Frozen] Mock <ILogger <DefaultRabbitMQPersistentConnection> > mockLogger, DefaultRabbitMQPersistentConnection sut ) { //Arrange //Act 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 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 Test2() { var manager = new InMemoryEventBusSubscriptionsManager(); 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); var result = manager.HasSubscriptionsForEvent("TestEvent"); ILogger <global::EventBusRabbitMQ.EventBusRabbitMQ> loggers = loggerFactory.CreateLogger <global::EventBusRabbitMQ.EventBusRabbitMQ>(); var builder = new ContainerBuilder(); var container = builder.Build(); var scope = container.BeginLifetimeScope(); IEventBus eventBus = new global::EventBusRabbitMQ.EventBusRabbitMQ(rabbitMqPersistentConnection, loggers, scope, manager, "TestEvent"); TestEvent testEvent = new TestEvent { Msg = "hello world" }; eventBus.Subscribe <TestEvent, TestIntegrationEventHandler>(); }
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); }