예제 #1
0
        public static void Receive()
        {
            var factory = RabbitHelper.GetFactory();

            using (var connection = factory.CreateConnection())
            {
                using (var model = connection.CreateModel())
                {
                    model.QueueDeclare(QueueName, true, false, false, null);
                    model.BasicQos(0, 1, false);

                    var consumer = new QueueingBasicConsumer(model);
                    model.BasicConsume(QueueName, false, consumer);

                    while (true)
                    {
                        var ea      = consumer.Queue.Dequeue();
                        var message = (Payment)ea.Body.DeSerialize(typeof(Payment));
                        model.BasicAck(ea.DeliveryTag, false);

                        Console.WriteLine("----- Payment Processed {0} : {1}", message.CardNumber, message.AmountToPay);
                    }
                }
            }
        }
        public List <WordBank> AddWordsToQueue(List <WordBank> words, WikiSession aSession)
        {
            for (var i = 0; i < words.Count(); i++)
            {
                var wbId   = words[i].WordBankId;
                var cached = _dbContext.WikiPages.FirstOrDefault(x => x.WordBankId == wbId);
                if (cached != null)
                {
                    continue;
                }
                var wordBank = _dbContext.WordBanks.FirstOrDefault(x => x.WordBankId == wbId);
                var wbq      = new WordBankQueue
                {
                    CreatedDate = DateTime.Now,
                    IsProcessed = false,
                    WordBankId  = wbId,
                    WordBank    = wordBank
                };

                _dbContext.WordBankQueues.Add(wbq);
                _dbContext.SaveChanges();
                _dbContext.Entry(wbq).Reload();

                wbq = RabbitHelper.Send(wbq, aSession); //Send items to RabbitMQ for processing

                words[i] = wbq.WordBank;
                words[i].WordBankQueues.Add(wbq);
            }

            return(words);
        }
예제 #3
0
        RabbitHelper rabbitHelper;         //rabbitHelper类

        public ConsumerServer()
        {
            RabbitMQSingleton rabbitMQSingleton             = RabbitMQSingleton.GetInstance();
            Dictionary <string, IConnection> connDictionary = rabbitMQSingleton.GetRabbitMQconn();

            if (connDictionary != null && connDictionary.Count > 0)
            {
                connection = connDictionary["test"];
            }
            else
            {
                HostModel hostModel = new HostModel();
                hostModel.UserName = "******";
                hostModel.PassWord = "******";
                hostModel.Host     = "127.0.0.1";
                hostModel.Port     = 5672;
                //hostModel.VirtualHost = "/";

                lock (obj)
                {
                    rabbitHelper = new RabbitHelper(hostModel);
                    connection   = rabbitHelper.Connection();
                    rabbitMQSingleton.SetRabbitMqConn("test", connection);
                }
            }
        }
    public async Task SendMessage(RequestMessage message)
    {
        var endpointConfiguration = new EndpointConfiguration("Samples.Docker.Sender");
        var transport             = endpointConfiguration.UseTransport <RabbitMQTransport>();

        transport.ConnectionString("host=rabbitmq");
        transport.UseConventionalRoutingTopology();
        var delayedDelivery = transport.DelayedDelivery();

        delayedDelivery.DisableTimeoutManager();
        endpointConfiguration.EnableInstallers();

        // The RabbitMQ container starts before endpoints but it may
        // take several seconds for the broker to become reachable.
        await RabbitHelper.WaitForRabbitToStart()
        .ConfigureAwait(false);

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Sending a message...");

        Console.WriteLine($"Requesting to get data by id: {message.Id:N}");

        await endpointInstance.Send("Samples.Docker.Receiver", message)
        .ConfigureAwait(false);

        Console.WriteLine("Message sent.");

        // Wait until the message arrives.
        _closingEvent.WaitOne();

        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
예제 #5
0
        public async Task <ActionResult <JObject> > Post([FromBody] JObject json)
        {
            var username = json["usr"]?.ToString();
            var command  = json["cmd"]?.ToString();

            if (command == "DUMPLOG" && string.IsNullOrEmpty(username))
            {
                username = "******";
            }

            if (string.IsNullOrEmpty(username))
            {
                return(BadRequest("No user specified"));
            }

            // Add a reference value so we can get response
            var reference = Guid.NewGuid().ToString("N");

            json.Add("ref", reference);

            var referenceCompletion = new TaskCompletionSource <JObject>();

            Program.PendingResponses.Add(reference, referenceCompletion);

            var instance = (username[1] % Program.Instances) + 1;

            try
            {
                RabbitHelper.PushCommand(json, instance);
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex.Message));
            }

            var timeoutCancellation = new CancellationTokenSource();
            var timeoutTask         = Task.Delay(60000).ContinueWith(t => {
                // Were we already canceled?
                if (timeoutCancellation.IsCancellationRequested)
                {
                    return(null);
                }

                var timeout = new JObject();
                timeout.Add("status", "error");
                timeout.Add("data", "Timed out waiting for reply from transaction server");

                Program.PendingResponses.Remove(reference);

                return(timeout);
            });

            var result = await(await Task.WhenAny(referenceCompletion.Task, timeoutTask));

            timeoutCancellation.Cancel();

            return(result);
        }
예제 #6
0
        /// <summary>
        /// Initialize new Worker
        /// </summary>
        private void StartWorker()
        {
            RabbitHelper rabbitWorker = new RabbitHelper();

            rabbitWorker.Initialize();
            rabbitWorker.Worker        = this.Worker++;
            rabbitWorker.ReceiveEvent += ReceivedHandlerCallback;
            rabbitWorker.ReceiveMessage(AppConfig.PARTNER_QUEUE);
            this.listRabbitWorker.Add(rabbitWorker);
            logger.Info(AppConst.A("StartWorker", rabbitWorker.Worker, AppConfig.PARTNER_QUEUE, "Started listener!"));
        }
예제 #7
0
    static async Task Main()
    {
        //required to prevent possible occurrence of .NET Core issue https://github.com/dotnet/coreclr/issues/12668
        Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
        Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-US");

        Console.CancelKeyPress += OnExit;

        Console.Title = "Samples.Docker.Sender";

        var endpointConfiguration = new EndpointConfiguration("Samples.Docker.Sender");
        var transport             = endpointConfiguration.UseTransport <RabbitMQTransport>();

        transport.ConnectionString("host=rabbitmq");
        transport.UseConventionalRoutingTopology();
        var delayedDelivery = transport.DelayedDelivery();

        delayedDelivery.DisableTimeoutManager();
        endpointConfiguration.EnableInstallers();

        // The RabbitMQ container starts before endpoints but it may
        // take several seconds for the broker to become reachable.
        await RabbitHelper.WaitForRabbitToStart()
        .ConfigureAwait(false);

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Sending a message...");

        var guid = Guid.NewGuid();

        Console.WriteLine($"Requesting to get data by id: {guid:N}");

        var message = new RequestMessage
        {
            Id   = guid,
            Data = "String property value"
        };

        await endpointInstance.Send("Samples.Docker.Receiver", message)
        .ConfigureAwait(false);

        Console.WriteLine("Message sent.");
        Console.WriteLine("Use 'docker-compose down' to stop containers.");

        // Wait until the message arrives.
        closingEvent.WaitOne();

        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
예제 #8
0
        static void Main()
        {
            _factory = RabbitHelper.GetFactory();
            using (_connection = _factory.CreateConnection())
            {
                using (var channel = _connection.CreateModel())
                {
                    var queueName = DeclareAndBindQueueToExchange(channel);
                    channel.BasicConsume(queueName, true, _consumer);

                    while (true)
                    {
                        var ea      = _consumer.Queue.Dequeue();
                        var message = (Payment)ea.Body.DeSerialize(typeof(Payment));

                        Console.WriteLine("----- Payment Processed {0} : {1}", message.CardNumber, message.AmountToPay);
                    }
                }
            }
        }
예제 #9
0
    static async Task Main()
    {
        Console.CancelKeyPress += OnExit;

        Console.Title = "Samples.Docker.Receiver";

        var endpointConfiguration = new EndpointConfiguration("Samples.Docker.Receiver");

        #region TransportConfiguration

        var transport = endpointConfiguration.UseTransport <RabbitMQTransport>();
        transport.ConnectionString("host=rabbitmq");
        transport.UseConventionalRoutingTopology();
        var delayedDelivery = transport.DelayedDelivery();
        delayedDelivery.DisableTimeoutManager();

        #endregion

        endpointConfiguration.EnableInstallers();

        // The RabbitMQ container starts before endpoints but it may
        // take several seconds for the broker to become reachable.
        #region WaitForRabbitBeforeStart
        await RabbitHelper.WaitForRabbitToStart()
        .ConfigureAwait(false);

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        #endregion

        Console.WriteLine("Use 'docker-compose down' to stop containers.");

        // Wait until the message arrives.
        closingEvent.WaitOne();

        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
예제 #10
0
 public TarifTenanController()
 {
     rabbitHelper = new RabbitHelper();
 }
예제 #11
0
        private void BtnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (String.IsNullOrEmpty(txtOracleConnection.Text))
                {
                    MessageBox.Show("Nhập chuỗi kết nối database!", "Thông báo");
                    return;
                }

                if (String.IsNullOrEmpty(cbbCountSMS.Text))
                {
                    MessageBox.Show("Nhập số lượng SMS trên 1 truy vấn!", "Thông báo");
                    return;
                }

                if (String.IsNullOrEmpty(txtRabbitConnection.Text))
                {
                    MessageBox.Show("Nhập chuỗi kết nối queue!", "Thông báo");
                    return;
                }

                if (String.IsNullOrEmpty(txtLimitLog.Text))
                {
                    MessageBox.Show("Giới hạn log không đúng", "Thông báo");
                    return;
                }

                SetTextMonitor("Push SMS to Queue start!", Color.Aqua);
                btnStart.Enabled            = false;
                btnStop.Enabled             = true;
                txtOracleConnection.Enabled = false;
                txtRabbitConnection.Enabled = false;
                cbbSmsType.Enabled          = false;
                cbbCountSMS.Enabled         = false;
                cbbMode.Enabled             = false;
                cbbInterval.Enabled         = false;
                txtLimitLog.Enabled         = false;

                this.rabbitHelper = new RabbitHelper();
                this.rabbitHelper.Initialize();

                if (cbbMode.SelectedIndex == 0)
                {
                    this.connection = new OracleConnection(txtOracleConnection.Text);

                    using (OracleCommand command = new OracleCommand((cbbSmsType.SelectedIndex == 0) ? AppConfig.QUERY_SELECT_SMS : AppConfig.QUERY_SELECT_CAMPAIGN, this.connection)
                    {
                        AddRowid = true
                    })
                    {
                        connection.Open();
                        this.oracleDependency           = new OracleDependency(command, false, 0, false);
                        this.oracleDependency.OnChange += new OnChangeEventHandler(OracleListenerCallback);
                        command.ExecuteNonQuery();
                        SetTextMonitor("Push SMS to Queue listener started!", Color.Aqua);
                    }

                    PushSMSToQueue();
                }
                else
                {
                    if (String.IsNullOrEmpty(cbbInterval.Text))
                    {
                        MessageBox.Show("Nhập interval!", "Thông báo");
                        return;
                    }

                    this.timer          = new Timer();
                    this.timer.Interval = Convert.ToInt32(cbbInterval.Text);
                    this.timer.Tick    += new EventHandler(TimerIntervalCallback);
                    this.timer.Start();
                    SetTextMonitor("Push SMS to Queue timer started!", Color.Aqua);
                }
            }
            catch (Exception ex)
            {
                btnStart.Enabled = true;
                btnStop.Enabled  = false;
                if (this.oracleDependency != null)
                {
                    this.oracleDependency.OnChange -= new OnChangeEventHandler(OracleListenerCallback);
                }
                SetTextMonitor("BtnStart_Click " + ex.ToString(), Color.Red);
                logger.Error("BtnStart_Click", ex);
            }
        }
예제 #12
0
 public MasterDataController()
 {
     response = new ImportProductResponse() { HasError = false, ErrorMessages = new List<String>() };
     rabbitHelper = new RabbitHelper();
 }