public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;
            _subscribeBus.Stop();
            GC.SuppressFinalize(this);
        }
예제 #2
0
        public bool Start(HostControl hostControl)
        {
            _log.Info("Creating bus...");
            _log.Info("Starting bus...");

            TaskUtil.Await(() => _busControl.StartAsync());
            var config = MassTransitConfigurationManager.Config;

            try
            {
                for (; ;)
                {
                    Console.Write("Enter Number (quit exits): ");
                    string customerId = Console.ReadLine();
                    if (customerId == "quit")
                    {
                        break;
                    }

                    // this is run as a Task to avoid weird console application issues
                    Task.Run(async() =>
                    {
                        //Request - Response
                        var response = await _generateScorecard.Request(new GenerateScorecardRequest {
                            WpbYear = int.Parse(customerId)
                        });
                        Console.WriteLine("This Is From Response: {0}", response.WpbYear);

                        //Send Command
                        var url          = config.Host + "/" + MassTransitQueue.GenerateScorecard;
                        var sendEndpoint = await _busControl.GetSendEndpoint(new Uri(url));
                        await sendEndpoint.Send <GenerateScorecard>(new
                        {
                            WpbYear = int.Parse(customerId)
                        });
                    }).Wait();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception!!! OMG!!! {0}", ex);
            }
            finally
            {
                _busControl.Stop();
            }

            return(true);
        }
예제 #3
0
 protected override void OnStop()
 {
     if (_busControl != null)
     {
         _busControl.Stop();
     }
 }
예제 #4
0
        static void Main(string[] args)
        {
            Console.Title = "Subscriber1";
            Console.WriteLine($"Subscriber1 start at {DateTime.Now}");

            IBusControl rabbitBusControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
            {
                IRabbitMqHost rabbitMqHost = rabbit.Host(new Uri("rabbitmq://localhost:5672"), settings =>
                {
                    settings.Password("ninisite");
                    settings.Username("ninisite");
                });

                rabbit.ReceiveEndpoint(rabbitMqHost, "masstransitsample.queues.events.subscriber1", conf =>
                {
                    //conf.PrefetchCount = 5;

                    conf.Consumer <Consumer>();
                });
            });

            rabbitBusControl.Start();
            Console.ReadKey();
            rabbitBusControl.Stop();
        }
예제 #5
0
        public bool Stop(HostControl hostControl)
        {
            _azureBus.Stop();
            _rabbitMqBus.Stop();

            return(true);
        }
        public async Task ShouldExecuteWorkflowRunsIndependently()
        {
            // Act
            _bus.Start();

            await _bus.Publish(new StartWorkflowMessage("X"));

            await _bus.Publish(new StartWorkflowMessage("Y"));

            var taskAXStarted = _observerX.TaskStartedHandle.WaitOne(TimeSpan.FromSeconds(5));
            await _bus.Publish(new CompleteTaskAMessage("X"));

            var taskAYStarted = _observerY.TaskStartedHandle.WaitOne(TimeSpan.FromSeconds(5));
            await _bus.Publish(new CompleteTaskAMessage("Y"));

            var taskBXStarted = _observerX.TaskStartedHandle.WaitOne(TimeSpan.FromSeconds(5));
            await _bus.Publish(new CompleteTaskBMessage("X"));

            var taskBYStarted = _observerY.TaskStartedHandle.WaitOne(TimeSpan.FromSeconds(5));
            await _bus.Publish(new CompleteTaskBMessage("Y"));

            var workflowXFinished = _observerX.WorkflowFinishedHandle.Wait(TimeSpan.FromSeconds(5));
            var workflowYFinished = _observerY.WorkflowFinishedHandle.Wait(TimeSpan.FromSeconds(5));

            _bus.Stop();

            Assert.True(workflowXFinished);
            Assert.True(workflowYFinished);
            Assert.Equal("@WF-@A-$A-@B-$B-$WF", _observerX.EventSequence);
            Assert.Equal("@WF-@A-$A-@B-$B-$WF", _observerY.EventSequence);
        }
예제 #7
0
        private void OnStopping()
        {
            // stop mass transit
            IBusControl busControl = Services.GetService <IBusControl>();

            busControl.Stop();
        }
예제 #8
0
파일: EventBus.cs 프로젝트: HP-dufeng/WIKI
 public void Stop()
 {
     if (_busControl != null)
     {
         _busControl.Stop();
     }
 }
예제 #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
        {
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ProductService.Stub V1");
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            lifetime.ApplicationStarted.Register(() => _bus.Start());
            lifetime.ApplicationStopping.Register(() => _bus.Stop());
        }
예제 #10
0
        /// <summary>
        ///
        /// </summary>
        // ReSharper disable once MethodNameNotMeaningful
        public override void Run()
        {
            InitLog();

            try
            {
                if (_listener == null)
                {
                    StartTcpListner();
                }
                //InitBus();
                //_bus.Start();
                while (true) // Add your exit flag here
                {
                    var client = _listener.AcceptTcpClient();
                    ThreadPool.QueueUserWorkItem(ThreadProc, client);
                }
            }
            catch (Exception exception)
            {
                _bus.Stop();
                Trace.TraceError(exception.Message);
            }
            finally
            {
                _runCompleteEvent.Set();
            }
        }
        public void SetupAzureServiceBusTestFixture()
        {
            _bus = CreateBus();

            _bus.ConnectReceiveEndpointObserver(new ReceiveEndpointObserver());

            _busHandle = _bus.Start();
            try
            {
                _busSendEndpoint = _bus.GetSendEndpoint(_bus.Address).Result;
                _busSendEndpoint.ConnectSendObserver(_sendObserver);

                _inputQueueSendEndpoint = _bus.GetSendEndpoint(_inputQueueAddress).Result;
                _inputQueueSendEndpoint.ConnectSendObserver(_sendObserver);
            }
            catch (Exception)
            {
                try
                {
                    using (var tokenSource = new CancellationTokenSource(TestTimeout))
                    {
                        _bus.Stop(tokenSource.Token);
                    }
                }
                finally
                {
                    _busHandle = null;
                    _bus       = null;
                }

                throw;
            }
        }
예제 #12
0
 public void Stop()
 {
     Log.Information("Viaduc service is stopping.");
     bus.Stop();
     Log.Information("Viaduc service has stopped.");
     Log.CloseAndFlush();
 }
 /// <summary>
 ///     Stops the ExternalContent Service.
 ///     Called by the service host when the service is stopped.
 /// </summary>
 public void Stop()
 {
     Log.Information("ExternalContent service is stopping");
     bus.Stop();
     Log.Information("ExternalContent service stopped");
     Log.CloseAndFlush();
 }
 public void Stop()
 {
     LogInformation("Notification service is stopping");
     bus.Stop();
     LogInformation("Notification service stopped");
     Log.CloseAndFlush();
 }
예제 #15
0
 /// <summary>
 ///     Stops the Harvest Service.
 ///     Called by the service host when the service is stopped.
 /// </summary>
 public void Stop()
 {
     Log.Information("Harvest service is stopping");
     bus.Stop();
     Log.Information("Harvest service stopped");
     Log.CloseAndFlush();
 }
예제 #16
0
 private void OnShutdown()
 {
     if (_messageBus != null)
     {
         _messageBus.Stop();
     }
 }
예제 #17
0
        public static async Task Run(IConfig config, List <string> parms)
        {
            if (parms.Count == 0)
            {
                Console.WriteLine("Missing queue name");
                return;
            }

            Console.WriteLine("Producer is running using queue {0}...", parms[0]);

            var host     = config.Get("host");
            var port     = config.GetInt("port");
            var username = config.Get("username");
            var password = config.Get("password");
            var queue    = parms[0];

            bus = CreateBus(host, port, username, password, queue);
            bus.Start();

            bool quit = false;

            while (!quit)
            {
                var msg = GetMessageFromUser();

                Console.WriteLine("Sending message...");
                Console.WriteLine("> {0}: '{1}'", msg.Author, msg.Text);

                await SendMessage <IMessageAdded>(bus, msg);

                quit = AskUserIfQuit();
            }

            bus.Stop();
        }
        public async Task ShouldExecuteWorkflow()
        {
            // Arrange
            var result = 0;

            var workflow = new ContextProcessingWorkflow(Multiply, number => result = number);
            var observer = new SingleWorkflowObserver <Context>(workflow, context => true);

            _bus = Bus.Factory.CreateUsingInMemory(sbc =>
            {
                sbc.ReceiveEndpoint("context_processing_workflow", ep => { ep.Workflow(workflow); });
            });

            // Act
            _bus.Start();

            await _bus.Publish(new StartWorkflowMessage(InitialNumber));

            var workflowFinished = observer.WorkflowFinishedHandle.Wait(TimeSpan.FromSeconds(5));

            _bus.Stop();

            // Assert
            Assert.True(workflowFinished);
            Assert.Equal(InitialNumber * Multiplier, result);
        }
예제 #19
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            lock (_disposing)
            {
                if (_disposed)
                {
                    return;
                }

                try
                {
                    _bus.Stop();
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Failed to stop MassTransit bus");
                }

                _disposing.Cancel();
                _disposing.Dispose();
                _semaphore.Dispose();

                _disposed = true;
            }
        }
 public override void Exit()
 {
     if (Control != null)
     {
         Control.Stop();
     }
 }
예제 #21
0
 public void Dispose()
 {
     if (_started)
     {
         _bus.Stop();
     }
 }
예제 #22
0
 public void Dispose()
 {
     if (_bus != null)
     {
         _bus.Stop();
     }
 }
예제 #23
0
        private static void RunMassTransitReceiverWithRabbitMq()
        {
            var         rabbitConfig     = RabbitConfigurationsLoader.LoadConfigurations(appsettingsFileName, true);
            IBusControl rabbitBusControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
            {
                var host = rabbit.Host(rabbitConfig.URL, "/", settings =>
                {
                    settings.Password(rabbitConfig.Password);
                    settings.Username(rabbitConfig.Username);
                });

                rabbit.ReceiveEndpoint(host, rabbitConfig.QueueName, conf =>
                {
                    conf.PrefetchCount      = rabbitConfig.MaxConcurrentMessages;
                    conf.ExchangeType       = rabbitConfig.ExchangeType;
                    conf.Durable            = rabbitConfig.Durable;
                    conf.AutoDelete         = rabbitConfig.AutoDelete;
                    conf.DeadLetterExchange = rabbitConfig.DeadLetterExchange;
                    conf.BindDeadLetterQueue(rabbitConfig.DeadLetterExchange, rabbitConfig.DeadLetterQueueName);
                    conf.UseMessageRetry(r => r.Interval(rabbitConfig.FailRetryCount, rabbitConfig.FailRetryInterval));
                    conf.Consumer <NotificationsConsumeHandler>();
                });
            });

            rabbitBusControl.Start();
            Console.ReadKey();
            rabbitBusControl.Stop();
        }
 /*
  * public async Task Reschedule<TMessage>(TimeSpan delay, TMessage message) where TMessage : class
  * {
  *  await _busControl.ScheduleSend<TMessage>(new Uri($"{_configuration["ServiceBus:Path"]}/quartz"), delay, message);
  * }
  */
 public void Dispose()
 {
     if (_busControl != null)
     {
         _busControl.Stop(TimeSpan.FromSeconds(30));
     }
 }
예제 #25
0
        private static void RunMessageBuss()
        {
            IBusControl rabbitBusControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
            {
                IRabbitMqHost rabbitMqHost = rabbit.Host(new Uri("rabbitmq://localhost:5672/payment"), settings =>
                {
                    settings.Password("guest");
                    settings.Username("guest");
                });

                rabbit.ReceiveEndpoint(rabbitMqHost, "superdigital.payments.events.resumeaccount", conf =>
                {
                    conf.PrefetchCount = 1;
                    conf.Consumer <PaymentCreatedConsumer>(paymentCreatedConfig =>
                    {
                        paymentCreatedConfig.UseContextFilter((context) =>
                        {
                            bool valid = context.TryGetMessage <IPaymentCreated>(out var message);
                            if (valid)
                            {
                                valid = message.Message?.CreatedBy == "wololo";
                                Console.WriteLine("Skipped message " + context.MessageId);
                            }

                            return(Task.FromResult(valid));
                        });
                    });
                });
            });

            rabbitBusControl.Start();
            Console.ReadKey();
            rabbitBusControl.Stop();
        }
예제 #26
0
        public bool Stop(HostControl hostControl)
        {
            _diagnostics.Stop();
            _busControl.Stop();

            return(true);
        }
        public void Run(CancellationToken cancellationToken = default(CancellationToken))
        {
            _capture = new MessageMetricCapture(_settings.MessageCount);

            IBusControl busControl = _transport.GetBusControl(ConfigureReceiveEndpoint);

            try
            {
                Console.WriteLine("Running Message Latency Benchmark");

                TaskUtil.Await(() => RunBenchmark(busControl), cancellationToken);

                Console.WriteLine("Message Count: {0}", _settings.MessageCount);
                Console.WriteLine("Clients: {0}", _settings.Clients);
                Console.WriteLine("Durable: {0}", _settings.Durable);
                Console.WriteLine("Payload Length: {0}", _payload?.Length ?? 0);
                Console.WriteLine("Prefetch Count: {0}", _settings.PrefetchCount);
                Console.WriteLine("Concurrency Limit: {0}", _settings.ConcurrencyLimit);

                Console.WriteLine("Total send duration: {0:g}", _sendDuration);
                Console.WriteLine("Send message rate: {0:F2} (msg/s)",
                                  _settings.MessageCount * 1000 / _sendDuration.TotalMilliseconds);
                Console.WriteLine("Total consume duration: {0:g}", _consumeDuration);
                Console.WriteLine("Consume message rate: {0:F2} (msg/s)",
                                  _settings.MessageCount * 1000 / _consumeDuration.TotalMilliseconds);
                Console.WriteLine("Concurrent Consumer Count: {0}", MessageLatencyConsumer.MaxConsumerCount);

                MessageMetric[] messageMetrics = _capture.GetMessageMetrics();

                Console.WriteLine("Avg Ack Time: {0:F0}ms",
                                  messageMetrics.Average(x => x.AckLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Min Ack Time: {0:F0}ms",
                                  messageMetrics.Min(x => x.AckLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Max Ack Time: {0:F0}ms",
                                  messageMetrics.Max(x => x.AckLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Med Ack Time: {0:F0}ms",
                                  messageMetrics.Median(x => x.AckLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("95t Ack Time: {0:F0}ms",
                                  messageMetrics.Percentile(x => x.AckLatency) * 1000 / Stopwatch.Frequency);

                Console.WriteLine("Avg Consume Time: {0:F0}ms",
                                  messageMetrics.Average(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Min Consume Time: {0:F0}ms",
                                  messageMetrics.Min(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Max Consume Time: {0:F0}ms",
                                  messageMetrics.Max(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("Med Consume Time: {0:F0}ms",
                                  messageMetrics.Median(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);
                Console.WriteLine("95t Consume Time: {0:F0}ms",
                                  messageMetrics.Percentile(x => x.ConsumeLatency) * 1000 / Stopwatch.Frequency);

                Console.WriteLine();
                DrawResponseTimeGraph(messageMetrics, x => x.ConsumeLatency);
            }
            finally
            {
                busControl.Stop();
            }
        }
예제 #28
0
 /// <summary>
 ///     Stops the Order Service.
 ///     Called by the service host when the service is stopped.
 /// </summary>
 public void Stop()
 {
     Log.Information("Order service is stopping");
     recalcTermineListener.Stop();
     bus.Stop();
     Log.Information("Order service stopped");
     Log.CloseAndFlush();
 }
        public virtual void Stop()
        {
            _logger.Info("Stopping service bus");

            _serviceBus.Stop();

            _logger.Info("Service bus stopped");
        }
예제 #30
0
        public void Configure(IApplicationBuilder app, IApplicationLifetime appLifetime)
        {
            app.UseAuthentication();
            app.UseMvc();

            appLifetime.ApplicationStarted.Register(() => _bus.Start());
            appLifetime.ApplicationStopping.Register(() => _bus.Stop());
        }
        public void SetupAzureServiceBusTestFixture()
        {
            _bus = CreateBus();

            _bus.ConnectReceiveEndpointObserver(new ReceiveEndpointObserver());

            _busHandle = _bus.Start();
            try
            {
                _busSendEndpoint = _bus.GetSendEndpoint(_bus.Address).Result;
                _busSendEndpoint.ConnectSendObserver(_sendObserver);

                _inputQueueSendEndpoint = _bus.GetSendEndpoint(_inputQueueAddress).Result;
                _inputQueueSendEndpoint.ConnectSendObserver(_sendObserver);
            }
            catch (Exception)
            {
                try
                {
                    using (var tokenSource = new CancellationTokenSource(TestTimeout))
                    {
                        _bus.Stop(tokenSource.Token);
                    }
                }
                finally
                {
                    _busHandle = null;
                    _bus = null;
                }

                throw;
            }
        }