Exemplo n.º 1
0
        public async Task <IActionResult> PostMessage(MessageDto messageDto)
        {
            var rabbitMqClient    = new RabbitMqClient();
            var serializedMessage = JsonConvert.SerializeObject(messageDto);
            var response          = rabbitMqClient.Call(serializedMessage);

            rabbitMqClient.Close();
            MessagePm deserializedResponse;

            try
            {
                deserializedResponse = JsonConvert.DeserializeObject <MessagePm>(response);
            }
            catch (Exception e)
            {
                return(StatusCode(500, e.Message));
            }

            _messageContext.Messages.Add(deserializedResponse);
            await _messageContext.SaveChangesAsync();

            var messageResponseDto = new MessageResponseDto
            {
                Id         = deserializedResponse.Id,
                ExternalId = deserializedResponse.ExternalId,
                Message    = deserializedResponse.Message
            };

            return(Ok(messageResponseDto));
        }
Exemplo n.º 2
0
        public async Task Handle(MetricQueryRequest <SingleNodeMemoryWidget> request, CancellationToken cancellationToken)
        {
            var ctx    = request.DataContext;
            var client = new RabbitMqClient(ctx.URL, ctx.Username, ctx.Password);

            try
            {
                var nodeInfo = await client.GetNodeInfoAsync(ctx.NodesUrlPath, ctx.NodeName)
                               .ConfigureAwait(false);

                if (!nodeInfo.IsMemoryHealthy(ctx.MaxMemoryUsagePercent, out _, out var memoryUsagePercent))
                {
                    ctx.Value = memoryUsagePercent;
                    ctx.State = State.Failed;
                }
                else
                {
                    ctx.Value = memoryUsagePercent;
                    ctx.State = State.Ok;
                }
            }
            catch (Exception e)
            {
                ctx.State   = State.Error;
                ctx.Message = e.Message;
            }
        }
Exemplo n.º 3
0
        private static void Publish()
        {
            var publisher = new RabbitMqClient(new RabbitConnectionParam()
            {
                HostName  = "localhost",
                UserName  = _username,
                Password  = _password,
                QueueName = _queuename,
                Vhost     = "/"
            });


            while (true)
            {
                Console.WriteLine("press 'q'+enter to exit");

                var read = Console.ReadLine();
                if (read.ToLower() == "q")
                {
                    break;
                }

                publisher.Publish(read);
            }
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Post([FromBody] RedisCreateModel model)
        {
            await _redisDatabase.StringSetAsync($"{model.Key}", model.Value);

            RabbitMqClient.Publish($"{model.Key} is successfully inserted into Redis");
            return(Ok());
        }
Exemplo n.º 5
0
        public async Task Handle(MetricQueryRequest <NodeDiskSpaceUsageWidget> request, CancellationToken cancellationToken)
        {
            var ctx    = request.DataContext;
            var client = new RabbitMqClient(ctx.URL, ctx.Username, ctx.Password);

            try
            {
                var nodeInfo = await client.GetNodeInfoAsync(ctx.NodesUrlPath, ctx.NodeName)
                               .ConfigureAwait(false);

                if (!nodeInfo.IsHasEnoughDiskSpace(ctx.MinFreeDiskSpacePercent, out _, out var diskSpaceUsedPercent))
                {
                    ctx.Value = diskSpaceUsedPercent;
                    ctx.State = State.Failed;
                }
                else
                {
                    ctx.Value = diskSpaceUsedPercent;
                    ctx.State = State.Ok;
                }
            }
            catch (Exception e)
            {
                ctx.State   = State.Error;
                ctx.Message = e.Message;
            }
        }
Exemplo n.º 6
0
 public Baggage()
 {
     cars        = new ConcurrentDictionary <string, BaggageCar>();
     tokens      = new ConcurrentDictionary <string, CancellationTokenSource>();
     mqClient    = new RabbitMqClient();
     sourceDelay = new PlayDelaySource(TimeSpeedFactor);
 }
Exemplo n.º 7
0
        public async Task Handle(HealthCheckRequest <PoliciesWidget> request, CancellationToken cancellationToken)
        {
            var ctx    = request.DataContext;
            var client = new RabbitMqClient(ctx.URL, ctx.Username, ctx.Password);

            try
            {
                var policies = await client.GetPoliciesAsync(ctx.PoliciesUrlPath, ctx.VirtualHost).ConfigureAwait(false);

                var missedPolicies = new List <string>();
                foreach (var requiredPolicy in ctx.RequiredPolicies)
                {
                    if (!policies.Any(x => x.Name == requiredPolicy))
                    {
                        missedPolicies.Add(requiredPolicy);
                    }
                }

                if (missedPolicies.Any())
                {
                    ctx.Message = "Missed policies: " + string.Join(", ", missedPolicies);
                    ctx.State   = State.Failed;
                }
                else
                {
                    ctx.State = State.Ok;
                }
            }
            catch (Exception e)
            {
                ctx.Message = e.Message;
                ctx.State   = State.Failed;
            }
        }
Exemplo n.º 8
0
        public async Task <RnnChiChatMessage> ProcessAsync(TextMessage message, string userContext, int replicCount)
        {
            using (RabbitMqClient client = new RabbitMqClient("localhost"))
            {
                string inputQueue = "RnnTalkService", outputQueue = "RnnTalkService";
                switch (message.Language)
                {
                case Language.English:
                    inputQueue  += "_input_en";
                    outputQueue += "_output_en";
                    break;

                case Language.Russian:
                    inputQueue  += "_input_ru";
                    outputQueue += "_output_ru";
                    break;

                default:
                    throw new Exceptions.InvalidMessageException(message.Id, "Invalid Language: " + message.Language.ToString());
                }

                RnnChiChatMessage talkSystemRequest = new RnnChiChatMessage();
                talkSystemRequest.Id              = message.Id;
                talkSystemRequest.TextData        = message.Text;
                talkSystemRequest.TalkContext     = userContext;
                talkSystemRequest.TalkReplicCount = replicCount;
                string responeRnn;
                responeRnn = await client.PostAsync(JsonConvert.SerializeObject(talkSystemRequest), inputQueue, outputQueue);

                var talkSystemRespone = JsonConvert.DeserializeObject <RnnChiChatMessage>(responeRnn);
                return(talkSystemRespone);
            }
        }
Exemplo n.º 9
0
 public DeicingComponent()
 {
     cars     = new ConcurrentDictionary <string, DeicingCar>();
     tokens   = new ConcurrentDictionary <string, CancellationTokenSource>();
     mqClient = new RabbitMqClient();
     source   = new PlayDelaySource(TimeSpeedFactor);
 }
Exemplo n.º 10
0
 public RabbitMqController(
     ConnectionFactory connectionFactory,
     RabbitMqClient rabbitMqClient)
 {
     _connectionFactory = connectionFactory;
     _rabbitMqClient    = rabbitMqClient;
 }
Exemplo n.º 11
0
 public TransportMotion(string Component, RabbitMqClient MqClient, PlayDelaySource source)
 {
     this.component = Component;
     this.mqClient  = MqClient;
     this.source    = source;
     CreateQueues();
     Subscribe();
 }
Exemplo n.º 12
0
 public FollowMeComponent()
 {
     MqClient = new RabbitMqClient();
     cars     = new ConcurrentDictionary <string, FollowMeCar>();
     tokens   = new ConcurrentDictionary <string, CancellationTokenSource>();
     source   = new PlayDelaySource(timeFactor);
     carTasks = new ConcurrentDictionary <string, Task>();
 }
Exemplo n.º 13
0
 public MessagingMiddleware(RabbitMqClient rabbitMqClient, RouteMatcher routeMatcher,
                            IOptions <MessagingOptions> messagingOptions)
 {
     _rabbitMqClient = rabbitMqClient;
     _routeMatcher   = routeMatcher;
     _endpoints      = messagingOptions.Value.Endpoints.GroupBy(e => e.Method.ToUpperInvariant())
                       .ToDictionary(e => e.Key, e => e.ToList());
 }
Exemplo n.º 14
0
 public void Start()
 {
     mqClient = new RabbitMqClient();
     CreateQueues();
     DeclareQueues();
     mqClient.PurgeQueues(queuesFrom.Values.ToArray());
     mqClient.PurgeQueues(queuesTo.Values.ToArray());
     Subscribe();
 }
 public GroundServiceCycles(RabbitMqClient mq, ILogger logger)
 {
     id          = count++;
     firstCycle  = new Cycle(logger, FirstCycleComponents);
     secondCycle = new Cycle(logger, SecondCycleComponents);
     this.logger = logger;
     mqClient    = mq;
     logger?.Debug($"{GroundServiceComponent.ComponentName}: Create new service cycle with Id {id} ");
 }
Exemplo n.º 16
0
        public void Start()
        {
            var mqClient = new RabbitMqClient();

            mqClient.DeclareQueues(
                TimetableToPassengerQueue,
                ScheduleToTimetableQueue,
                TimeServiceToTimetableQueue,
                TimeServiceToTimetableFactorQueue
                );

            mqClient.PurgeQueues(
                TimetableToPassengerQueue,
                ScheduleToTimetableQueue,
                TimeServiceToTimetableQueue,
                TimeServiceToTimetableFactorQueue
                );

            var timetable = new ConsoleTimetable();

            mqClient.SubscribeTo <CurrentPlayTime>(TimeServiceToTimetableQueue, (mes) =>
            {
                lock (timetable)
                {
                    timetable.SetCurrentTime(mes.PlayTime);
                    timetable.Draw();
                }
            });

            mqClient.SubscribeTo <NewTimeSpeedFactor>(TimeServiceToTimetableFactorQueue, (mes) =>
            {
                source.TimeFactor = mes.Factor;
            });

            mqClient.SubscribeTo <FlightStatusUpdate>(ScheduleToTimetableQueue, (mes) =>
            {
                lock (timetable)
                {
                    // TODO if flight is departed, then remove it in N minutes
                    timetable.UpdateFlight(mes);
                    mqClient.Send(TimetableToPassengerQueue, new Timetable()
                    {
                        Flights = timetable.GetTimetable()
                    });
                    if (mes.Status == FlightStatus.Departed)
                    {
                        Task.Run(() =>
                        {
                            source.CreateToken().Sleep(TIME_TILL_REMOVING_DEPARTED_FLIGHT_MS);
                            lock (timetable) {
                                timetable.RemoveFlight(mes.FlightId);
                            }
                        });
                    }
                }
            });
        }
Exemplo n.º 17
0
 public BusComponent()
 {
     mqClient         = new RabbitMqClient();
     cars             = new ConcurrentDictionary <string, BusCar>();
     commands         = new ConcurrentQueue <PassengersServiceCommand>();
     completionEvents = new ConcurrentDictionary <string, CountdownEvent>();
     playDelaySource  = new PlayDelaySource(timeFactor);
     transportMotion  = new TransportMotion.TransportMotion(Component.Bus, mqClient, playDelaySource);
 }
Exemplo n.º 18
0
 public void Start(RabbitMqClient client)
 {
     LogManager.Configuration = new XmlLoggingConfiguration("NLog.config");
     logger   = LogManager.GetCurrentClassLogger();
     MqClient = client;
     CreateQueues();
     DeclareQueues();
     MqClient.PurgeQueues(queuesFrom.Values.ToArray());
     Subscribe();
 }
Exemplo n.º 19
0
 public FuelTruck()
 {
     mqClient         = new RabbitMqClient();
     cars             = new ConcurrentDictionary <string, FuelTruckCar>();
     commands         = new ConcurrentQueue <RefuelServiceCommand>();
     completionEvents = new ConcurrentDictionary <string, CountdownEvent>();
     tokens           = new ConcurrentDictionary <string, CancellationTokenSource>();
     playDelaySource  = new PlayDelaySource(timeFactor);
     transportMotion  = new TransportMotion.TransportMotion(Component.FuelTruck, mqClient, playDelaySource);
 }
 public BookingService(
     BookingRepository bookingRepository,
     RabbitMqClient eventBus,
     ICustomerServiceApiClient customerServiceApiClient,
     ICorrelationContextAccessor correlationContext)
 {
     _bookingRepository        = bookingRepository;
     _eventBus                 = eventBus;
     _customerServiceApiClient = customerServiceApiClient;
     _correlationContext       = correlationContext;
 }
 public OrderCommandHandler(
     IOrderRepository orderRepository,
     ICustomerServiceApiClient customerServiceApiClient,
     ICorrelationContextAccessor correlationContext,
     RabbitMqClient rabbitMqClient)
 {
     _orderRepository          = orderRepository;
     _customerServiceApiClient = customerServiceApiClient;
     _correlationContext       = correlationContext;
     _rabbitMqClient           = rabbitMqClient;
 }
        public async Task <IActionResult> Post([FromBody] TodoListModel model)
        {
            if (model != null)
            {
                _dbContext.Add(model);
                await _dbContext.SaveChangesAsync();

                RabbitMqClient.Publish($"New todo item was successfully inserted into MS-SQL - > {model.Description}");
                return(Ok());
            }
            return(BadRequest());
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            try
            {
                RabbitMqClient     rabbitInterceptor = new RabbitMqClient();
                MessageInterceptor interceptor       = new MessageInterceptor(rabbitInterceptor);

                interceptor.InterceptMessage();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occurred receiving message: " + ex.ToString());
            }
        }
Exemplo n.º 24
0
 /// <summary>
 /// Publish ToggleState updated message
 /// </summary>
 /// <param name="toggleState"></param>
 private void PublishToggleState(ToggleState toggleState)
 {
     if (toggleState != null && toggleState.Toggle != null && toggleState.Service != null)
     {
         RabbitMqClient.Publish(
             new TogglerStateMessage
         {
             ToggleKey  = toggleState.Toggle.Key,
             Value      = toggleState.Value,
             ServiceKey = toggleState.Service.Key
         },
             toggleState.Service.Key
             );
     }
 }
Exemplo n.º 25
0
        public async Task Handle(HealthCheckRequest <QueueStatsWidget> request, CancellationToken cancellationToken)
        {
            var ctx    = request.DataContext;
            var client = new RabbitMqClient(ctx.URL, ctx.Username, ctx.Password);

            try
            {
                var queueStatistics = await client
                                      .GetQueueStatisticsAsync(ctx.QueuesUrlPath, ctx.VirtualHost)
                                      .ConfigureAwait(false);

                var tooMuchMessagesQueues =
                    queueStatistics
                    .Where(x => x.Messages > ctx.MaxMessagesInQueue && new Regex(ctx.QueueFilterRegex).IsMatch(x.Name))
                    .Select(x => $"{x.Name} has {x.Messages} messages. ConsumersCount: {x.Consumers}");

                var totalMessagesSum = queueStatistics.Sum(x => x.Messages);

                var errorMessage = string.Empty;

                if (totalMessagesSum >= ctx.MaxMessagesInAllQueues)
                {
                    errorMessage = "Max messages exceeded: " + totalMessagesSum + " of " +
                                   ctx.MaxMessagesInAllQueues + Environment.NewLine;
                }

                if (tooMuchMessagesQueues.Any())
                {
                    errorMessage += string.Join(";" + Environment.NewLine, tooMuchMessagesQueues) + ";";
                }

                if (!string.IsNullOrEmpty(errorMessage))
                {
                    ctx.Message = errorMessage;
                    ctx.State   = State.Failed;
                }
                else
                {
                    ctx.State   = State.Ok;
                    ctx.Message = null;
                }
            }
            catch (Exception e)
            {
                ctx.Message = e.Message;
                ctx.State   = State.Failed;
            }
        }
Exemplo n.º 26
0
        public async Task Handle(HealthCheckRequest <ClusterHealthCheckWidget> request,
                                 CancellationToken cancellationToken)
        {
            var ctx    = request.DataContext;
            var client = new RabbitMqClient(ctx.URL, ctx.Username, ctx.Password);

            try
            {
                var nodesInfo = await client.GetNodeInfosAsync(ctx.NodesUrlPath).ConfigureAwait(false);

                var errors = new List <string>();
                foreach (var nodeInfo in nodesInfo)
                {
                    var error = string.Empty;

                    if (!nodeInfo.IsMemoryHealthy(ctx.MaxMemoryUsagePercent, out var memoryErrorMessage, out _))
                    {
                        error += memoryErrorMessage;
                    }

                    if (!nodeInfo.IsHasEnoughDiskSpace(ctx.MinFreeDiskSpacePercent, out var usedDiskSpaceError, out _))
                    {
                        error += usedDiskSpaceError;
                    }

                    if (!string.IsNullOrEmpty(error))
                    {
                        error = "For node " + nodeInfo.NodeName + " " + error;
                        errors.Add(error);
                    }
                }

                if (errors.Any())
                {
                    ctx.Message = string.Join(", ", errors);
                    ctx.State   = State.Failed;
                }
                else
                {
                    ctx.State = State.Ok;
                }
            }
            catch (Exception e)
            {
                ctx.State   = State.Failed;
                ctx.Message = e.Message;
            }
        }
Exemplo n.º 27
0
            public override async Task <TextProcessingServiceRespone> Invork(TextRequest textRequest)
            {
                using (RabbitMqClient client = new RabbitMqClient("localhost"))
                {
                    var time = DateTime.Now;

                    string inputQueue = "RnnTalkService", outputQueue = "RnnTalkService";
                    TextProcessingServiceRespone respone = new TextProcessingServiceRespone
                    {
                        Id         = textRequest.Id.Value,
                        IntentName = "none",
                        TextData   = ""
                    };
                    if (_language == Enums.Language.English)
                    {
                        inputQueue  += "_input_en";
                        outputQueue += "_output_en";
                    }
                    else if (_language == Enums.Language.Russian)
                    {
                        inputQueue  += "_input_ru";
                        outputQueue += "_output_ru";
                    }

                    DbClient db      = new DbClient();
                    var      context = await db.GetContext(textRequest.Id.Value);

                    RnnTalkSystemRequest talkSystemRequest = new RnnTalkSystemRequest();
                    talkSystemRequest.Id              = textRequest.Id;
                    talkSystemRequest.TextData        = textRequest.TextData;
                    talkSystemRequest.TalkContext     = context.TalkContext;
                    talkSystemRequest.TalkReplicCount = context.TalkReplicCount;
                    string responeRnn;
                    responeRnn = await client.PostAsync(JsonConvert.SerializeObject(talkSystemRequest), inputQueue, outputQueue);

                    var talkSystemRespone = JsonConvert.DeserializeObject <RnnTalkSystemRespone>(responeRnn);
                    context.TalkContext     = talkSystemRespone.TalkContext;
                    context.TalkReplicCount = talkSystemRespone.TalkReplicCount;
                    await db.AddOrUpdateContext(context);

                    respone.TextData = talkSystemRespone.TextData;
                    db.Dispose();
                    Log.LogInformation(textRequest.Id.Value, 0, this.GetType().ToString(), $"service end work in {(DateTime.Now - time).Milliseconds} ms");

                    return(respone);
                }
            }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            var messageProvider = MessageProviderFactory.GetProvider(ProviderType.Numbers);
            var rabbit          = new RabbitMqClient();

            rabbit.CreateQueue(QueueName);

            while (true)
            {
                var message = messageProvider.GetMessage();

                Console.WriteLine($"Publish: {message}");
                rabbit.PublishMessage(message.TransformToByte(), QueueName);

                Thread.Sleep(300);
            }
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            try
            {
                RabbitMqClient rabbitDispatcher = new RabbitMqClient();

                Console.WriteLine("Enter a name: ");
                string name = Console.ReadLine();

                MessageDispatcher dispatcher = new MessageDispatcher(rabbitDispatcher, name);
                dispatcher.DispatchMessage();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occurred dispatching message: " + ex.ToString());
            }
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            var rabbit = new RabbitMqClient();

            rabbit.SubscribeOnQueue((model, arg) =>
            {
                var body = arg.Body;
                Console.WriteLine(body.TransformToString());
            }, QueueName);

            Console.WriteLine("=========");

            var result = rabbit.WaitMessageFromQueue(QueueName);

            Console.WriteLine(result.TransformToString());

            Console.ReadKey();
        }
Exemplo n.º 31
0
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);

            Log.Info("Version 0.5.3");

            this.rabbitMqClient = new RabbitMqClient();

            var basePath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            this.plansDir = Path.Combine(basePath, "plans");

            if (!Directory.Exists(plansDir))
            {
                Directory.CreateDirectory(plansDir);
            }

            this.thread = new Thread(Loop);
            this.thread.Start();
        }