Пример #1
0
        static void Main()
        {
            //set up the Mongo connection
            const string connectionString = "mongodb://192.168.182.1";
            var          client           = new MongoClient(connectionString);
            var          server           = client.GetServer();
            var          database         = server.GetDatabase("BackEnd");

            //set up unity
            var container = new UnityContainer();

            var typesToRegister =
                typeof(Program).Assembly.GetTypes().Where(
                    x => !x.IsGenericType && x.GetInterfaces().Contains(typeof(IConsumer)));

            foreach (var type in typesToRegister)
            {
                container.RegisterType(type);
            }

            container.RegisterInstance(database);

            //set up the message bus
            var messageBus = ServiceBusFactory.New(config => {
                config.UseMsmq();
                config.VerifyMsmqConfiguration();
                config.UseMulticastSubscriptionClient();

                config.ReceiveFrom("msmq://localhost/BackEnd");

                //config.UseRabbitMq();
                //config.ReceiveFrom("rabbitmq://localhost/BackEnd");

                config.Subscribe(x => x.LoadFrom(container));
            });

            container.RegisterInstance(messageBus);

            //wait for messages
            Console.WriteLine("Hit enter to close");

            Console.ReadLine();

            messageBus.Dispose();
        }
Пример #2
0
        public static NodeContext ConnectNode(string host, NodeRecord node,
                                              Func <object, object> transportSpecificQueueNameTranslator,
                                              Action <ServiceBusConfigurator> customBusConfiguration = null)
        {
            transportSpecificQueueNameTranslator = transportSpecificQueueNameTranslator ?? MsmqTransportTranslator;
            dynamic queueSpecs = transportSpecificQueueNameTranslator(new
            {
                Format     = "uri",
                Host       = host,
                NodeRecord = node
            });

            Uri receiveFromUri = new Uri(queueSpecs.Uri);
            Action <ServiceBusConfigurator> sbcOps = queueSpecs.SBCAdjustments;
            TransportSettings ts = new TransportSettings
            {
                PrimaryHost       = host,
                ProtocolUriPrefix = queueSpecs.Prefix
            };

            var serviceBus = ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom(receiveFromUri);

                sbcOps(sbc);

                sbc.UseControlBus();
                //sbc.EnableRemoteIntrospection();

                if (customBusConfiguration != null)
                {
                    customBusConfiguration(sbc);
                }
            });



            return(new NodeContext
            {
                Record = node,
                Bus = serviceBus,
                QueueName = queueSpecs.QueueName,
                Settings = ts
            });
        }
        public void An_interface_based_message_is_published()
        {
            _receivedAnyRat = new TaskCompletionSource <CorrelatedTestMessage>();

            var details = new AccountDetails();

            _subscriberBus = ServiceBusFactory.New(sbc =>
            {
                var uri = details.BuildUri("test_subscriber");
                Console.WriteLine(uri);

                sbc.ReceiveFrom(uri);
                sbc.SetPurgeOnStartup(true);
                sbc.Subscribe(s => s.Handler <CorrelatedTestMessage>(x => _receivedAnyRat.TrySetResult(x)).Transient());
                sbc.UseAzureServiceBus(x =>
                {
                    x.ConfigureNamespace(uri.Host, h =>
                    {
                        h.SetKeyName(AccountDetails.KeyName);
                        h.SetKey(AccountDetails.Key);
                    });
                });
                sbc.UseAzureServiceBusRouting();
            });

            _publisherBus = ServiceBusFactory.New(sbc =>
            {
                var uri = details.BuildUri("test_publisher");
                sbc.ReceiveFrom(uri);
                sbc.SetPurgeOnStartup(true);
                sbc.UseAzureServiceBus(x =>
                {
                    x.ConfigureNamespace(uri.Host, h =>
                    {
                        h.SetKeyName(AccountDetails.KeyName);
                        h.SetKey(AccountDetails.Key);
                    });
                });
                sbc.UseAzureServiceBusRouting();
            });


            _correlationId = NewId.NextGuid();
            _publisherBus.Publish <CorrelatedTestMessage>(new CorrelatedTestMessageImpl(_correlationId, "meek"));
        }
        /// <summary>
        /// Loads the specified builder.
        /// </summary>
        /// <param name="builder">The builder.</param>
        protected override void Load(ContainerBuilder builder)
        {
            // register each consumer manually
            //builder.RegisterType<YourConsumer>().As<IConsumer>();

            //or use Autofac's scanning capabilities -- SomeClass is any class in the correct assembly
            //builder.RegisterAssemblyTypes(typeof(SomeClass).Assembly).As<IConsumer>();


            builder.Register(
                c => ServiceBusFactory.New(
                    sbc =>
            {
                // other configuration options
                sbc.UseMsmq(configurator => configurator.VerifyMsmqConfiguration());

                sbc.UseXmlSerializer();
                sbc.EnableMessageTracing();

                sbc.ReceiveFrom(QueueUtility.QueueName);

                //var container = AdvanceOfMassTransit.container;
                //Subscribe dựa vào việc load từ container những class nào kế thừa IConsumer để làm
                //sẽ tương đương:
                //sbc.Subscribe(x =>
                //{
                //    x.Consumer<StudentConsumer>();
                //});
                //Subscribe tự theo dõi nếu có queue nào cùng kiểu thì chạy luôn function Consume(IConsumeContext<T> message) của class đó

                sbc.Subscribe(x => x.LoadFrom(c.Resolve <ILifetimeScope>()));
                sbc.SetConcurrentConsumerLimit(1);

                // sbc.UseControlBus();
            })).As <IServiceBus>().SingleInstance();

            if (registerConsumers)
            {
                builder.RegisterAssemblyTypes(GetType().Assembly)
                .Where(t => t.Implements <IConsumer>())
                .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies)
                .InstancePerDependency()
                .AsSelf();
            }
        }
        public void Creating_a_queue_with_transactional_enabled()
        {
            _address = new MsmqEndpointAddress(new Uri("msmq://localhost/created_transactional"));

            if (MessageQueue.Exists(_address.LocalName))
            {
                MessageQueue.Delete(_address.LocalName);
            }

            _bus = ServiceBusFactory.New(x =>
            {
                x.UseMsmq();
                x.ReceiveFrom(_address.Uri);

                x.SetCreateMissingQueues(true);
                x.SetCreateTransactionalQueues(true);
            });
        }
Пример #6
0
        static void CreateServiceContainer()
        {
            var coreContainer = new WindsorContainer();

            coreContainer.AddFacility <TypedFactoryFacility>();
            coreContainer.Register(Component.For <Service>(),
                                   Component.For <IServiceBus>().UsingFactoryMethod((k, c) =>
            {
                return(ServiceBusFactory.New(sbc =>
                {
                    sbc.UseRabbitMqRouting();
                    sbc.ReceiveFrom(ServiceUri);
                    sbc.Subscribe(s => s.LoadFrom(coreContainer));
                }));
            }).LifeStyle.Singleton);

            _coreBus = coreContainer.Resolve <IServiceBus>();
        }
Пример #7
0
        public void Should_allow_class_level_environments()
        {
            using (IServiceBus bus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom("loopback://localhost/my_queue");
                x.SetReceiveTimeout(10.Milliseconds());

                x.Environments(e =>
                {
                    e.Add <Production>();

                    e.Select("production");
                });
            }))
            {
                ((ServiceBus)bus).MaximumConsumerThreads.ShouldEqual(7);
            }
        }
Пример #8
0
        public void Should_validate_against_null()
        {
            try
            {
                using (ServiceBusFactory.New(x =>
                {
                    x.ReceiveFrom("loopback://localhost/a");
                    x.UseBusBuilder(null);
                }))
                {
                }

                Assert.Fail("bus builder was set to null");
            }
            catch (ConfigurationException)
            {
            }
        }
        static IServiceBus GetServiceBus(IConfiguration configuration)
        {
            return(ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom(configuration.TimeoutServiceDataUri);
                sbc.UseControlBus();
                sbc.UseLog4Net();

                sbc.UseMsmq(x => x.UseSubscriptionService(configuration.SubscriptionServiceUri));

                sbc.SetConcurrentConsumerLimit(1);

                if (configuration.HealthServiceEnabled)
                {
                    sbc.UseHealthMonitoring(10);
                }
            }));
        }
Пример #10
0
        public void Configuring_the_distributor_side()
        {
            IServiceBus bus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom("loopback://localhost/queue");

                x.Distributor(d =>
                {
                    d.Handler <A>()
                    .UseWorkerSelector(() => new LeastBusyWorkerSelectorFactory())
                    .UseWorkerSelector <LeastBusyWorkerSelectorFactory>();

                    d.Consumer <MyConsumer>();

                    d.Saga <MySaga>(new InMemorySagaRepository <MySaga>());
                });
            });
        }
Пример #11
0
        public void AllNonCompetingHandlersShouldReceiveComands()
        {
            using (var serviceBus = ServiceBusFactory.New(bus =>
            {
                bus.ReceiveFrom(Config.CommandPublisherAddress);

                bus.UseRabbitMq();
            }))
                using (var handler1 = new TestCommandHandler(new Uri(Config.CommandHandlerAddress1), "TestCommandHandler1", 1))
                    using (var handler2 = new TestCommandHandler(new Uri(Config.CommandHandlerAddress2), "TestCommandHandler2", 1))
                    {
                        serviceBus.Publish(new TestCommand());

                        handler1.CommandReceived.WaitUntilCompleted(10.Seconds());
                        handler2.CommandReceived.WaitUntilCompleted(10.Seconds());
                        Assert.IsTrue(handler1.CommandReceived.IsCompleted && handler2.CommandReceived.IsCompleted);
                    }
        }
        public void Configure()
        {
            try
            {
                Bus = ServiceBusFactory.New(sbc =>
                {
                    sbc.UseLog4Net();
                    sbc.UseRabbitMq();
                    sbc.ReceiveFrom("rabbitmq://localhost/greeting_saga");

                    sbc.Subscribe(subs => subs.Saga(new InMemorySagaRepository <AuctionSaga>()));
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        protected override void EstablishContext()
        {
            base.EstablishContext();

            SubscriptionBus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom(SubscriptionServiceUri);
                x.SetConcurrentConsumerLimit(1);
            });

            SetupSubscriptionService();

            SetupLocalBus();

            SetupRemoteBus();

            Instances = new Dictionary <string, ServiceInstance>();
        }
Пример #14
0
        private static IServiceBus CreateBus(IContext context)
        {
            var bus = ServiceBusFactory.New(cfg =>
            {
                cfg.DisablePerformanceCounters();
                cfg.ReceiveFrom("rabbitmq://localhost/cqrs-poc");
                cfg.UseRabbitMq(cf =>
                {
                    cf.ConfigureHost(new Uri("rabbitmq://localhost/cqrs-poc"), hc =>
                    {
                        hc.SetUsername("petcar");
                        hc.SetPassword("?!Krone2009");
                    });
                });
            });

            return(bus);
        }
Пример #15
0
        public DoWork()
        {
            DataBus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom(ConfigurationManager.AppSettings["SourceQueue"]);
                x.SetPurgeOnStartup(true);

                x.UseMsmq();
                x.UseMulticastSubscriptionClient();
                x.UseControlBus();

                x.SetConcurrentConsumerLimit(4);

                x.Worker(w => w.Consumer <SimpleWorkItemConsumer>());
            });

            ControlBus = DataBus.ControlBus;
        }
Пример #16
0
        public void Should_allow_inline_environment()
        {
            using (IServiceBus bus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom("loopback://localhost/my_queue");
                x.SetReceiveTimeout(10.Milliseconds());

                x.Environments(e =>
                {
                    e.Add("development", y => { y.SetConcurrentConsumerLimit(1); });

                    e.Select("development");
                });
            }))
            {
                ((ServiceBus)bus).MaximumConsumerThreads.ShouldEqual(1);
            }
        }
Пример #17
0
 protected override void Load(ContainerBuilder builder)
 {
     builder.Register(c => ServiceBusFactory.New
                      (
                          sbc =>
     {
         sbc.UseMsmq(x =>
         {
             x.VerifyMsmqConfiguration();
             x.UseMulticastSubscriptionClient();
         });
         sbc.ReceiveFrom(c.Resolve <IApplicationSettings>().WebMessageQueueAddress);
     }
                      )
                      )
     .As <IServiceBus>()
     .SingleInstance();
 }
Пример #18
0
        public CollectCompletedWork()
        {
            DataBus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom(ConfigurationManager.AppSettings["SourceQueue"]);
                x.SetPurgeOnStartup(true);

                x.UseMsmq();
                x.UseMulticastSubscriptionClient();
                x.UseControlBus();

                x.SetConcurrentConsumerLimit(4);

                x.Distributor(d => d.Handler <DoSimpleWorkItem>());
            });

            ControlBus = DataBus.ControlBus;
        }
Пример #19
0
        public static IServiceBus ConfigureMassTransit(string queueAddress, Action <ServiceBusConfigurator> additionalConfiguration = null)
        {
            if (queueAddress == null)
            {
                throw new ArgumentNullException("queueAddress");
            }

            return(ServiceBusFactory.New(sbc =>
            {
                sbc.SetPurgeOnStartup(true);
                sbc.UseRabbitMq();
                //sbc.UseLog4Net();
                sbc.ReceiveFrom(queueAddress);
                if (additionalConfiguration != null)
                {
                    additionalConfiguration(sbc);
                }
            }));
        }
        private void ConfigurePublisher(Uri receiveFrom, Uri hostUrl)
        {
            //var configurator = new RoutingConfigurator();
            //configurator.Route<TestMessage>().To(hostUrl);

            _publisher = ServiceBusFactory.New(config =>
            {
                config.UseAzureServiceBus(a => a.ConfigureNamespace(AccountDetails.Namespace, h =>
                {
                    h.SetKeyName(AccountDetails.KeyName);
                    h.SetKey(AccountDetails.Key);
                }));
                config.UseAzureServiceBusRouting();
                config.ReceiveFrom(receiveFrom);
            });

            //var bus = configurator.Create(_publisher);
            //bus.Start(_publisher);
        }
    public void Configure()
    {
        if (_queue == Queue.Worker)
        {
            foreach (var consumer in _consumers)
            {
                _kernel.Bind(consumer).ToSelf();
            }
            foreach (var massTransitConsumer in _massTransitConsumers)
            {
                _kernel.Bind(massTransitConsumer).ToSelf();
            }
        }

        var massTransitServiceBus = ServiceBusFactory.New(ConfigureMassTransit);
        var ourServiceBus         = new MassTransitServiceBus(massTransitServiceBus);

        _kernel.Bind <OurDomain.IServiceBus>().ToConstant(ourServiceBus);
    }
Пример #22
0
        private static void RegisterTypes(IUnityContainer container, Action <ServiceBusConfigurator> extraConfig)
        {
            container.RegisterInstance <IServiceBus>(ServiceBusFactory.New(sbc =>
            {
                sbc.UseRabbitMq();
                sbc.ReceiveFrom($"{_rabbitMQBaseUri}{_queueName}");

                sbc.SetDefaultRetryLimit(_retryLimit);
                sbc.DisablePerformanceCounters();

                if (extraConfig != null)
                {
                    extraConfig(sbc);
                }
            }));

            container.RegisterType <IRepository <CourseSubscription>, EFRepository <CourseSubscription> >(
                new InjectionConstructor(new OnlineCoursesDbContext()));
        }
Пример #23
0
        public void Should_allow_selection_by_app_setting()
        {
            using (IServiceBus bus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom("loopback://localhost/my_queue");
                x.SetReceiveTimeout(10.Milliseconds());

                x.Environments(e =>
                {
                    e.Add <Production>();
                    e.Add <Development>();

                    e.SelectByAppSetting("environmentName");
                });
            }))
            {
                ((ServiceBus)bus).MaximumConsumerThreads.ShouldEqual(1);
            }
        }
        /// <summary>
        /// Defaults the bus creator.
        /// </summary>
        /// <param name="serviceLocator">The service locator.</param>
        /// <returns></returns>
        public static IServiceBus DefaultBusCreator(IServiceLocator serviceLocator)
        {
            if (serviceLocator == null)
            {
                serviceLocator = ServiceLocatorManager.Current;
            }
            var bus = ServiceBusFactory.New(sbc =>
            {
                sbc.UseMsmq();
                sbc.UseMulticastSubscriptionClient();
                sbc.ReceiveFrom("msmq://localhost/test_queue");
                sbc.Subscribe(subs =>
                {
                    //subs.Handler<YourMessage>(msg=>Console.WriteLine(msg.Text));
                });
            });

            return(bus);
        }
Пример #25
0
 public IServiceBus Initialize(Action <SubscriptionBusServiceConfigurator> subscribe, Action <ServiceBusConfigurator> configure)
 {
     if (_initialized)
     {
         return(ServiceBus);
     }
     ServiceBus = ServiceBusFactory.New(sbc =>
     {
         configure(sbc);
         if (subscribe != null)
         {
             sbc.Subscribe(subscribe);
         }
     });
     ServiceBus.Probe();
     ServiceBus.WriteIntrospectionToConsole();
     _initialized = true;
     return(ServiceBus);
 }
Пример #26
0
        public bool Start(HostControl hostControl)
        {
            var kernel = new StandardKernel();

            kernel.Bind <IServiceBus>().ToConstant(ServiceBusFactory.New(sbc =>
            {
                sbc.ReceiveFrom("rabbitmq://localhost/queue");
                sbc.UseRabbitMq();
                sbc.Subscribe(subs => subs.Consumer <HospitalConsumer>(kernel));
                sbc.Subscribe(subs => subs.Consumer <LoginConsumer>(kernel));
                sbc.SetConcurrentConsumerLimit(10);
            }));

            kernel.Bind <HospitalConsumer>().ToSelf();
            kernel.Bind <DataManager <Hospital> >().ToSelf().InSingletonScope();
            kernel.Bind <DataManager <Login> >().ToSelf().InSingletonScope();

            return(true);
        }
Пример #27
0
        private static void EventStoreTest()
        {
            Guid StreamId = Guid.NewGuid();
            var  bus      = ServiceBusFactory.New(sbc =>
            {
            });

            var store = Wireup.Init()
                        .LogToOutputWindow()
                        .UsingInMemoryPersistence()
                        .UsingSqlPersistence("EventStoreConnection") // Connection string is in app.config
                        .WithDialect(new MsSqlDialect())
                        .EnlistInAmbientTransaction()                // two-phase commit
                        .InitializeStorageEngine()
                        .TrackPerformanceInstance("example")
                        .UsingJsonSerialization()
                        .Compress()
                        .EncryptWith(EncryptionKey)
                        .HookIntoPipelineUsing(new[] { new AuthorizationPipelineHook() })
                        .UsingSynchronousDispatchScheduler()
                        .DispatchTo(new DelegateMessageDispatcher(DispatchCommit))
                        .Build();

            using (store)
            {
                using (var stream = store.CreateStream(StreamId))
                {
                    stream.Add(new EventMessage()
                    {
                        Body = "Hello World!"
                    });
                    stream.CommitChanges(StreamId);
                }

                using (var stream = store.OpenStream(StreamId, 0, int.MinValue))
                {
                    foreach (var evnt in stream.CommittedEvents)
                    {
                        Console.WriteLine(evnt.Body);
                    }
                }
            }
        }
Пример #28
0
        public void Configuring_the_worker_side()
        {
            IServiceBus bus = ServiceBusFactory.New(x =>
            {
                x.ReceiveFrom("loopback://localhost/queue");

                x.Worker(w =>
                {
                    w.Handler <A>(message => { });
                    w.Handler <A>((context, message) => { });

                    w.Consumer <MyConsumer>();
                    w.Consumer(() => new MyConsumer());
                    w.Consumer(typeof(MyConsumer), Activator.CreateInstance);

                    w.Saga(new InMemorySagaRepository <MySaga>());
                });
            });
        }
        private void StartTimeoutService(TransportSettings settings)
        {
            //
            // setup the time out service
            //
            string subscriptionQueueUri = settings.GetQueueUri(SubscriptionServiceQueueName ?? STR_DefaultSubscriptionServiceQueueName);
            string timeoutQueueUri      = settings.GetQueueUri(TimeoutServiceQueueName ?? STR_DefaultTimeoutServiceQueueName);
            var    timeoutBus           = ServiceBusFactory.New(sbc =>
            {
                sbc.UseControlBus();

                sbc.ReceiveFrom(timeoutQueueUri);
                sbc.UseSubscriptionService(subscriptionQueueUri);
            });

            var timeoutService = new TimeoutService(timeoutBus, new InMemorySagaRepository <TimeoutSaga>());

            timeoutService.Start();
        }
Пример #30
0
        public ConsumerRegistry()
        {
            Scan(x =>
            {
                x.TheCallingAssembly();
                x.WithDefaultConventions();
                x.LookForRegistries();
            });

            For <IServiceBus>().Use(ServiceBusFactory.New(cfg =>
            {
                cfg.UseRabbitMq();

                // NOTE: Notice that this is a different queue than the other consumer of the same message
                cfg.ReceiveFrom("rabbitmq://localhost/Subscriber.CooperatingConsumer");

                cfg.Subscribe(s => s.Consumer <MultiConsumerMessageConsumer>());
            }));
        }