Ejemplo n.º 1
0
        public GreetingService()
        {
            log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingEvent>, GreetingEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingEvent, GreetingEventHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            //create the gateway
            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnnection);

            _dispatcher = DispatchBuilder.With()
                          .CommandProcessor(CommandProcessorBuilder.With()
                                            .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                            .Policies(policyRegistry)
                                            .NoTaskQueues()
                                            .RequestContextFactory(new InMemoryRequestContextFactory())
                                            .Build())
                          .MessageMappers(messageMapperRegistry)
                          .DefaultChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory))
                          .Connections(new []
            {
                new Connection <GreetingEvent>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("greeting.event"),
                    new RoutingKey("greeting.event"),
                    timeoutInMilliseconds: 200)
            }).Build();
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingEvent>, GreetingEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingEvent, GreetingEventHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            //create the gateway
            var redisConnection = new RedisMessagingGatewayConfiguration
            {
                RedisConnectionString = "localhost:6379?connectTimeout=1&sendTImeout=1000&",
                MaxPoolSize           = 10,
                MessageTimeToLive     = TimeSpan.FromMinutes(10)
            };

            var redisConsumerFactory = new RedisMessageConsumerFactory(redisConnection);

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(CommandProcessorBuilder.With()
                                               .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                               .Policies(policyRegistry)
                                               .NoTaskQueues()
                                               .RequestContextFactory(new InMemoryRequestContextFactory())
                                               .Build())
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new ChannelFactory(redisConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <GreetingEvent>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("greeting.event"),
                    new RoutingKey("greeting.event"),
                    timeoutInMilliseconds: 200)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press Enter to stop ...");
            Console.ReadLine();

            dispatcher.End().Wait();
        }
Ejemplo n.º 3
0
        private static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Warning()
                         .WriteTo.Console()
                         .CreateLogger();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IAmACommandCounter, CommandCounter>();
            container.Register <IHandleRequests <CompetingConsumerCommand>, CompetingConsumerCommandHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <CompetingConsumerCommand, CompetingConsumerCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(CompetingConsumerCommand), typeof(CompetingConsumerCommandMessageMapper) }
            };

            //create the gateway
            var messagingConfiguration =
                new MsSqlMessagingGatewayConfiguration(
                    @"Database=BrighterSqlQueue;Server=.\sqlexpress;Integrated Security=SSPI;", "QueueData");
            var messageConsumerFactory = new MsSqlMessageConsumerFactory(messagingConfiguration);

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(CommandProcessorBuilder.With()
                                               .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                               .Policies(policyRegistry)
                                               .NoTaskQueues()
                                               .RequestContextFactory(new InMemoryRequestContextFactory())
                                               .Build())
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new ChannelFactory(messageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <CompetingConsumerCommand>(
                    new ConnectionName("paramore.example.multipleconsumer.command"),
                    new ChannelName("multipleconsumer.command"),
                    new RoutingKey("multipleconsumer.command"),
                    timeoutInMilliseconds: 200)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press Enter to stop receiving ...");
            Console.ReadLine();

            dispatcher.End().Wait();

            var count = container.Resolve <IAmACommandCounter>().Counter;


            Console.WriteLine($"There were {count} commands handled by this consumer");
            Console.WriteLine("Press Enter to exit ...");
            Console.ReadLine();
        }
Ejemplo n.º 4
0
        public TaskMailerService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var container = new TinyIoCContainer();

            container.Register <IAmAMessageMapper <TaskReminderCommand>, Tasks.Ports.TaskReminderCommandMessageMapper>();
            container.Register <MailTaskReminderHandler, MailTaskReminderHandler>();
            container.Register <IAmAMailGateway, MailGateway>();
            container.Register <IAmAMailTranslator, MailTranslator>();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <TaskReminderCommand, MailTaskReminderHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(TaskReminderCommand), typeof(TaskReminderCommandMessageMapper) },
                { typeof(TaskReminderSentEvent), typeof(TaskReminderSentEventMapper) }
            };
            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            var commandProcessor = CommandProcessorBuilder.With()
                                   .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                   .Policies(policyRegistry)
                                   .TaskQueues(new MessagingConfiguration(new TemporaryMessageStore(), new RmqMessageProducer(rmqConnnection), messageMapperRegistry))
                                   .RequestContextFactory(new InMemoryRequestContextFactory())
                                   .Build();

            container.Register <IAmACommandProcessor>(commandProcessor);

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnnection);
            var rmqMessageProducerFactory = new RmqMessageProducerFactory(rmqConnnection);

            var connections = new List <Connection>
            {
                new Connection <TaskReminderCommand>(new ConnectionName("Task.Reminder"), new ChannelName("Task.Reminder"), new RoutingKey("Task.Reminder"))
            };

            _dispatcher = DispatchBuilder.With()
                          .CommandProcessor(commandProcessor)
                          .MessageMappers(messageMapperRegistry)
                          .DefaultChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory))
                          .Connections(connections)
                          .Build();
        }
Ejemplo n.º 5
0
        public DocumentService()
        {
            log4net.Config.XmlConfigurator.Configure();


            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <DocumentCreatedEvent>, DocumentCreatedEventHandler>();
            container.Register <IHandleRequests <DocumentUpdatedEvent>, DocumentUpdatedEventHandler>();
            container.Register <IHandleRequests <FolderCreatedEvent>, FolderCreatedEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <DocumentCreatedEvent, DocumentCreatedEventHandler>();
            subscriberRegistry.Register <DocumentUpdatedEvent, DocumentUpdatedEventHandler>();
            subscriberRegistry.Register <FolderCreatedEvent, FolderCreatedEventHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(5000),
                TimeSpan.FromMilliseconds(10000),
                TimeSpan.FromMilliseconds(10000)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(FolderCreatedEvent), typeof(FolderCreatedEventMessageMapper) },
                { typeof(DocumentCreatedEvent), typeof(DocumentCreatedEventMessageMapper) },
                { typeof(DocumentUpdatedEvent), typeof(DocumentUpdatedEventMessageMapper) }
            };

            var awsCredentials = new StoredProfileAWSCredentials();


            var sqsMessageConsumerFactory = new SqsMessageConsumerFactory(awsCredentials);
            var sqsMessageProducerFactory = new SqsMessageProducerFactory(awsCredentials);

            var connections = new List <Connection>
            {
                new Connection(
                    new ConnectionName("paramore.example.documentsandfolders.documentcreatedevent"),
                    new InputChannelFactory(sqsMessageConsumerFactory, sqsMessageProducerFactory),
                    typeof(DocumentCreatedEvent),
                    new ChannelName("https://sqs.eu-west-1.amazonaws.com/027649620536/DocumentCreatedEvent"),
                    "DocumentCreatedEvent",
                    timeoutInMilliseconds: 5000,
                    noOfPerformers: 10),
                new Connection(
                    new ConnectionName("paramore.example.documentsandfolders.documentupdatedevent"),
                    new InputChannelFactory(sqsMessageConsumerFactory, sqsMessageProducerFactory),
                    typeof(DocumentUpdatedEvent),
                    new ChannelName("https://sqs.eu-west-1.amazonaws.com/027649620536/DocumentUpdatedEvent"),
                    "DocumentUpdatedEvent",
                    timeoutInMilliseconds: 5000,
                    noOfPerformers: 10),
                new Connection(
                    new ConnectionName("paramore.example.documentsandfolders.foldercreateddevent"),
                    new InputChannelFactory(sqsMessageConsumerFactory, sqsMessageProducerFactory),
                    typeof(FolderCreatedEvent),
                    new ChannelName("https://sqs.eu-west-1.amazonaws.com/027649620536/FolderCreatedEvent"),
                    "FolderCreatedEvent",
                    timeoutInMilliseconds: 5000,
                    noOfPerformers: 10)
            };



            var builder = DispatchBuilder
                          .With()
                          .CommandProcessor(CommandProcessorBuilder.With()
                                            .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                            .Policies(policyRegistry)
                                            .NoTaskQueues()
                                            .RequestContextFactory(new InMemoryRequestContextFactory())
                                            .Build()
                                            )
                          .MessageMappers(messageMapperRegistry)
                          .ChannelFactory(new InputChannelFactory(sqsMessageConsumerFactory, sqsMessageProducerFactory))
                          .Connections(connections);

            _dispatcher = builder.Build();
        }
        public ManagementAndMonitoringService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingCommand>, GreetingCommandHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingCommand, GreetingCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingCommand), typeof(GreetingCommandMessageMapper) }
            };

            //create the gateway
            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory("messages");
            var rmqMessageProducerFactory = new RmqMessageProducerFactory("messages");

            var builder = DispatchBuilder
                          .With()
                          .CommandProcessor(CommandProcessorBuilder.With()
                                            .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                            .Policies(policyRegistry)
                                            .NoTaskQueues()
                                            .RequestContextFactory(new InMemoryRequestContextFactory())
                                            .Build()
                                            )
                          .MessageMappers(messageMapperRegistry)
                          .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory))
                          .ConnectionsFromConfiguration();

            _dispatcher = builder.Build();

            var controlBusBuilder = ControlBusReceiverBuilder
                                    .With()
                                    .Dispatcher(_dispatcher)
                                    .ProducerFactory(rmqMessageProducerFactory)
                                    .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory, rmqMessageProducerFactory)) as ControlBusReceiverBuilder;

            _controlDispatcher = controlBusBuilder.Build(Environment.MachineName + "." + "ManagementAndMonitoring");

            container.Register <IAmAControlBusSender>(new ControlBusSenderFactory().Create(
                                                          new MsSqlMessageStore(
                                                              new MsSqlMessageStoreConfiguration(
                                                                  "DataSource=\"" + Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(8)), "App_Data\\MessageStore.sdf") + "\"", "Messages",
                                                                  MsSqlMessageStoreConfiguration.DatabaseType.SqlCe)
                                                              ),
                                                          new RmqMessageProducer("monitoring")));
        }
Ejemplo n.º 7
0
        public static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();

            var container            = new TinyIoCContainer();
            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingCommand>, GreetingCommandHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingCommand, GreetingCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingCommand), typeof(GreetingCommandMessageMapper) }
            };

            var rmqGatewayMessages = RmqGatewayBuilder.With
                                     .Uri(new Uri("amqp://*****:*****@localhost:5672/%2f"))
                                     .Exchange("paramore.brighter.exchange")
                                     .DefaultQueues();

            var rmqMessageProducerFactory = new RmqMessageProducerFactory(rmqGatewayMessages);

            var inputChannelFactory = new InputChannelFactory(new RmqMessageConsumerFactory(rmqGatewayMessages), rmqMessageProducerFactory);
            var builder             = DispatchBuilder
                                      .With()
                                      .CommandProcessor(CommandProcessorBuilder.With()
                                                        .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                                        .Policies(policyRegistry)
                                                        .NoTaskQueues()
                                                        .RequestContextFactory(new InMemoryRequestContextFactory())
                                                        .Build()
                                                        )
                                      .MessageMappers(messageMapperRegistry)
                                      .ChannelFactory(inputChannelFactory)
                                      .Connections(new[]
            {
                ConnectionBuilder.With
                .Name("paramore.example.greeting")
                .ChannelFactory(inputChannelFactory)
                .Type(typeof(GreetingCommand))
                .ChannelName("greeting.event")
                .RoutingKey("greeting.event")
                .Timeout(200)
                .Build()
            });

            _dispatcher = builder.Build();

            var controlBusBuilder = ControlBusReceiverBuilder
                                    .With()
                                    .Dispatcher(_dispatcher)
                                    .ProducerFactory(rmqMessageProducerFactory)
                                    .ChannelFactory(inputChannelFactory) as ControlBusReceiverBuilder;
            var controlDispatcher = controlBusBuilder.Build(Environment.MachineName + "." + "ManagementAndMonitoring");

            container.Register <IAmAControlBusSender>(new ControlBusSenderFactory().Create(
                                                          new SqliteMessageStore(
                                                              new SqliteMessageStoreConfiguration(
                                                                  "DataSource=\"" + Path.Combine(Path.GetDirectoryName(typeof(GreetingCommand).GetTypeInfo().Assembly.CodeBase.Substring(8)), "App_Data\\MessageStore.sdf") + "\"", "Messages")
                                                              ),
                                                          new RmqMessageProducer(RmqGatewayBuilder.With
                                                                                 .Uri(new Uri("amqp://*****:*****@localhost:5672/%2f"))
                                                                                 .Exchange("paramore.brighter.exchange")
                                                                                 .DefaultQueues())));

            controlDispatcher.Receive();
            _dispatcher.Receive();

            Console.WriteLine("Press Enter to stop ...");
            Console.ReadLine();

            controlDispatcher.End();   //Don't wait on the control bus, we are stopping so we don't want any more control messages, just terminate
            _dispatcher.End().Wait();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Builds this instance.
        /// </summary>
        /// <param name="hostName">Name of the host.</param>
        /// <returns>Dispatcher.</returns>
        public Dispatcher Build(string hostName)
        {
            // We want to register policies, messages and handlers for receiving built in commands. It's simple enough to do this for
            // the registries, but we cannot know your HandlerFactory implementation in order to insert. So we have to rely on
            // an internal HandlerFactory to build these for you.
            // We also need to  pass the supervised dispatcher as a dependency to our command handlers, so this allows us to manage
            // the injection of the dependency as part of our handler factory

            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy },
                { CommandProcessor.RETRYPOLICY, retryPolicy }
            };

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <ConfigurationCommand, ConfigurationCommandHandler>();
            subscriberRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandHandler>();

            var incomingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            incomingMessageMapperRegistry.Register <ConfigurationCommand, ConfigurationCommandMessageMapper>();
            incomingMessageMapperRegistry.Register <HeartbeatRequest, HeartbeatRequestCommandMessageMapper>();

            var outgoingMessageMapperRegistry = new MessageMapperRegistry(new ControlBusMessageMapperFactory());

            outgoingMessageMapperRegistry.Register <HeartbeatReply, HeartbeatReplyCommandMessageMapper>();

            //TODO: It doesn't feel quite right that we have to pass this in for both dispatcher channel factory and task queue configuration
            //as we should be over same broker. But, so far, refactoring either ends up exposing properties of the channel factory, which we don't want
            //or stalling on the need for channel factory to be broker defined. It is possible the fix is to drop channel factory in favour of passing
            //in producer and sender. But that's a breaking change to the builder, so contemplating for now.

            var producer = _producerFactory.Create();

            var messageStore = new SinkMessageStore();

            CommandProcessor commandProcessor = null;

            commandProcessor = CommandProcessorBuilder.With()
                               .Handlers(new HandlerConfiguration(subscriberRegistry, new ControlBusHandlerFactory(_dispatcher, () => commandProcessor)))
                               .Policies(policyRegistry)
                               .TaskQueues(new MessagingConfiguration(messageStore, producer, outgoingMessageMapperRegistry))
                               .RequestContextFactory(new InMemoryRequestContextFactory())
                               .Build();

            // These are the control bus channels, we hardcode them because we want to know they exist, but we use
            // a base naming scheme to allow centralized management.
            var connectionsConfiguration = new Connection[]
            {
                new Connection <ConfigurationCommand>(
                    new ConnectionName($"{hostName}.{CONFIGURATION}"),
                    new ChannelName($"{hostName}.{CONFIGURATION}"),
                    new RoutingKey($"{hostName}.{CONFIGURATION}")),
                new Connection <HeartbeatRequest>(
                    new ConnectionName($"{hostName}.{HEARTBEAT}"),
                    new ChannelName($"{hostName}.{HEARTBEAT}"),
                    new RoutingKey($"{hostName}.{HEARTBEAT}"))
            };

            return(DispatchBuilder.With()
                   .CommandProcessor(commandProcessor)
                   .MessageMappers(incomingMessageMapperRegistry)
                   .DefaultChannelFactory(_channelFactory)
                   .Connections(connectionsConfiguration)
                   .Build());
        }
Ejemplo n.º 9
0
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.LiterateConsole()
                         .CreateLogger();

            var container = new TinyIoCContainer();

            var handlerFactory       = new TinyIocHandlerFactory(container);
            var messageMapperFactory = new TinyIoCMessageMapperFactory(container);

            container.Register <IHandleRequests <GreetingEvent>, GreetingEventHandler>();

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <GreetingEvent, GreetingEventHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory)
            {
                { typeof(GreetingEvent), typeof(GreetingEventMessageMapper) }
            };

            //create the gateway
            var rmqConnnection = new RmqMessagingGatewayConnection
            {
                AmpqUri  = new AmqpUriSpecification(new Uri("amqp://*****:*****@localhost:5672/%2f")),
                Exchange = new Exchange("paramore.brighter.exchange"),
            };

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(rmqConnnection);

            var dispatcher = DispatchBuilder.With()
                             .CommandProcessor(CommandProcessorBuilder.With()
                                               .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                               .Policies(policyRegistry)
                                               .NoTaskQueues()
                                               .RequestContextFactory(new InMemoryRequestContextFactory())
                                               .Build())
                             .MessageMappers(messageMapperRegistry)
                             .DefaultChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory))
                             .Connections(new Connection[]
            {
                new Connection <GreetingEvent>(
                    new ConnectionName("paramore.example.greeting"),
                    new ChannelName("greeting.event"),
                    new RoutingKey("greeting.event"),
                    timeoutInMilliseconds: 200,
                    isDurable: true,
                    highAvailability: true)
            }).Build();

            dispatcher.Receive();

            Console.WriteLine("Press Enter to stop ...");
            Console.ReadLine();

            dispatcher.End().Wait();
        }
Ejemplo n.º 10
0
        public OrderService()
        {
            log4net.Config.XmlConfigurator.Configure();

            var logger = LogProvider.For <OrderService>();

            var container = new UnityContainer();

            container.RegisterInstance(typeof(ILog), LogProvider.For <OrderService>(), new ContainerControlledLifetimeManager());
            container.RegisterType <AddOrderCommandMessageMapper>();
            container.RegisterType <OrderUpdateCommandMessageMapper>();
            container.RegisterType <AddOrderCommandHandler>();
            container.RegisterType <CompleteOrderCommandHandler>();
            container.RegisterType <EditOrderCommandHandler>();
            container.RegisterType <OrderUpdateCommandHandler>();
            container.RegisterType <IOrdersDAO, OrdersDAO>();

            var handlerFactory       = new UnityHandlerFactory(container);
            var messageMapperFactory = new UnityMessageMapperFactory(container);

            var subscriberRegistry = new SubscriberRegistry();

            subscriberRegistry.Register <AddOrderCommand, AddOrderCommandHandler>();
            subscriberRegistry.Register <CompleteOrderCommand, CompleteOrderCommandHandler>();
            subscriberRegistry.Register <EditOrderCommand, EditOrderCommandHandler>();
            subscriberRegistry.Register <OrderUpdateCommand, OrderUpdateCommandHandler>();

            //create policies
            var retryPolicy = Policy
                              .Handle <Exception>()
                              .WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(150)
            });

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(500));

            var policyRegistry = new PolicyRegistry()
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            };

            var commandProcessor = CommandProcessorBuilder.With()
                                   .Handlers(new HandlerConfiguration(subscriberRegistry, handlerFactory))
                                   .Policies(policyRegistry)
                                   .Logger(logger)
                                   .NoTaskQueues()
                                   .RequestContextFactory(new InMemoryRequestContextFactory())
                                   .Build();

            //create message mappers
            var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory);

            messageMapperRegistry.Register <AddOrderCommand, AddOrderCommandMessageMapper>();

            var rmqMessageConsumerFactory = new RmqMessageConsumerFactory(logger);

            _dispatcher = DispatchBuilder.With()
                          .Logger(logger)
                          .CommandProcessor(commandProcessor)
                          .MessageMappers(messageMapperRegistry)
                          .ChannelFactory(new InputChannelFactory(rmqMessageConsumerFactory))
                          .ConnectionsFromConfiguration()
                          .Build();
        }
Ejemplo n.º 11
0
        private static CommandProcessor BuildCommandProcessor(IServiceProvider provider)
        {
            var options            = provider.GetService <IBrighterOptions>();
            var subscriberRegistry = provider.GetService <ServiceCollectionSubscriberRegistry>();
            var useRequestResponse = provider.GetService <IUseRpc>();

            var handlerFactory       = new ServiceProviderHandlerFactory(provider);
            var handlerConfiguration = new HandlerConfiguration(subscriberRegistry, handlerFactory);

            var messageMapperRegistry = MessageMapperRegistry(provider);

            var outbox      = provider.GetService <IAmAnOutboxSync <Message> >();
            var asyncOutbox = provider.GetService <IAmAnOutboxAsync <Message> >();
            var overridingConnectionProvider = provider.GetService <IAmABoxTransactionConnectionProvider>();

            if (outbox == null)
            {
                outbox = new InMemoryOutbox();
            }
            if (asyncOutbox == null)
            {
                asyncOutbox = new InMemoryOutbox();
            }

            var inboxConfiguration = provider.GetService <InboxConfiguration>();

            var producerRegistry = provider.GetService <IAmAProducerRegistry>();

            var needHandlers = CommandProcessorBuilder.With();

            var featureSwitchRegistry = provider.GetService <IAmAFeatureSwitchRegistry>();

            if (featureSwitchRegistry != null)
            {
                needHandlers = needHandlers.ConfigureFeatureSwitches(featureSwitchRegistry);
            }

            var policyBuilder = needHandlers.Handlers(handlerConfiguration);

            var messagingBuilder = options.PolicyRegistry == null
                ? policyBuilder.DefaultPolicy()
                : policyBuilder.Policies(options.PolicyRegistry);

            var loggerFactory = provider.GetService <ILoggerFactory>();

            ApplicationLogging.LoggerFactory = loggerFactory;

            var commandProcessor = AddExternalBusMaybe(
                options,
                producerRegistry,
                messagingBuilder,
                messageMapperRegistry,
                inboxConfiguration,
                outbox,
                overridingConnectionProvider,
                useRequestResponse)
                                   .RequestContextFactory(options.RequestContextFactory)
                                   .Build();

            return(commandProcessor);
        }