コード例 #1
0
 public virtual void Dispose()
 {
     ConnectionHandler?.Dispose();
     ConnectionHandler = null;
     LogDispatcher?.Dispose();
     LogDispatcher = null;
 }
コード例 #2
0
        public void ProcessMessage(IConnectionHandler connection, ConcurrentDictionary <string, IConnectionHandler> connectionHandlers, IMessageHandler messageHandler)
        {
            IConnectionHandler handler;
            string             responseMessage = string.Empty;

            if (!connectionHandlers.ContainsKey(this.Contents))
            {
                //Remove the place holder name with login name and broadcast login ack to everyone
                connectionHandlers.TryRemove(connection.Name, out handler);
                connectionHandlers.TryAdd(this.Contents, connection);
                connection.Name = this.Contents;

                responseMessage = connectionHandlers.Keys.Aggregate(string.Empty, (current, userName) => current + "|" + userName);

                IMessage response = messageHandler.GetMessage(this.Contents, "all", responseMessage, MessageCommand.LoginAck);

                foreach (IConnectionHandler connectionHandler in connectionHandlers.Values)
                {
                    connectionHandler.SendMessage(response);
                }
            }
            else
            {
                //Login in use don't; kill connection and nack the request to the otherside
                connectionHandlers.TryRemove(connection.Name, out handler);

                responseMessage = "Login already in use";
                IMessage response = messageHandler.GetMessage("server", connection.Name, responseMessage, MessageCommand.LoginNack);

                connection.SendMessage(response);
                connection.Dispose();
            }
        }
コード例 #3
0
        /// <summary>
        /// Dispose of the brokerage instance
        /// </summary>
        public override void Dispose()
        {
            PricingConnectionHandler.ConnectionLost     -= OnPricingConnectionLost;
            PricingConnectionHandler.ConnectionRestored -= OnPricingConnectionRestored;
            PricingConnectionHandler.ReconnectRequested -= OnPricingReconnectRequested;
            PricingConnectionHandler.Dispose();

            TransactionsConnectionHandler.ConnectionLost     -= OnTransactionsConnectionLost;
            TransactionsConnectionHandler.ConnectionRestored -= OnTransactionsConnectionRestored;
            TransactionsConnectionHandler.ReconnectRequested -= OnTransactionsReconnectRequested;
            TransactionsConnectionHandler.Dispose();
        }
コード例 #4
0
        public void ProcessMessage(IConnectionHandler connection, ConcurrentDictionary <string, IConnectionHandler> connectionHandlers, IMessageHandler handler)
        {
            IConnectionHandler placeHolder;

            connectionHandlers.TryRemove(this.Sender, out placeHolder);
            connection.Dispose();

            IResponse response = handler.GetResponse(this.Sender, "all", this.Contents,
                                                     MessageCommand.DisconnectResponse);

            foreach (IConnectionHandler connectionHandler in connectionHandlers.Values)
            {
                connectionHandler.SendMessage(response);
            }
        }
コード例 #5
0
        /// <summary>
        /// Dispose of the brokerage instance
        /// </summary>
        public override void Dispose()
        {
            Aggregator.DisposeSafely();
            _refreshEvent.DisposeSafely();

            _streamingCancellationTokenSource.Cancel();

            PricingConnectionHandler.ConnectionLost     -= OnPricingConnectionLost;
            PricingConnectionHandler.ConnectionRestored -= OnPricingConnectionRestored;
            PricingConnectionHandler.ReconnectRequested -= OnPricingReconnectRequested;
            PricingConnectionHandler.Dispose();

            TransactionsConnectionHandler.ConnectionLost     -= OnTransactionsConnectionLost;
            TransactionsConnectionHandler.ConnectionRestored -= OnTransactionsConnectionRestored;
            TransactionsConnectionHandler.ReconnectRequested -= OnTransactionsReconnectRequested;
            TransactionsConnectionHandler.Dispose();
        }
コード例 #6
0
        public void Publish(T message, string routingKey = null)
        {
            // TODO connection persistence, stop lots of connections
            try
            {
                if (!_connected)
                {
                    _connection = _connectionFactory.CreateConnection(_publisherConfig.Name, _cancellationToken);

                    _channel = _connection.CreateModel();

                    lock (_lock)
                    {
                        _connected = true;
                    }
                }

                var body = Encoding.UTF8.GetBytes(_serializer.SerializeObject(message));

                _channel.BasicPublish(exchange: _publisherConfig.ExchangeName,
                                      routingKey: !string.IsNullOrEmpty(routingKey) ? routingKey : _publisherConfig.RoutingKey,
                                      basicProperties: null,
                                      body: body);
                _logger.Info($"Sent message");
            }
            catch (Exception ex)
            {
                _logger.Error($"An unexpected exception occurred, error details '{ex.Message}'", ex);

                lock (_lock)
                {
                    _connected = false;
                }

                if (_channel != null)
                {
                    _channel.Dispose();
                }

                if (_connection != null)
                {
                    _connection.Dispose();
                }
            }
        }
コード例 #7
0
        public void Run(Func <QueueMessage <T>, CancellationToken, Task> onMessageReceived, CancellationToken cancellationToken)
        {
            if (onMessageReceived == null)
            {
                throw new ArgumentNullException(nameof(onMessageReceived));
            }

            try
            {
                if (!_connected)
                {
                    _connection = _connectionFactory.CreateConnection(_consumerConfig.Name, cancellationToken);

                    _channel = _connection.CreateModel();
                    _channel.BasicQos(0, _queueConfiguration.MessagePrefetchCount, false);

                    var consumer = new EventingBasicConsumer(_channel);
                    consumer.Received += async(model, rabbitMessage) =>
                    {
                        await ProcessMessageAsync(model, rabbitMessage, onMessageReceived, cancellationToken);
                    };

                    var dynamicQueue = $"{_queueConfiguration.TemporaryQueueNamePrefix}_{Guid.NewGuid().ToString()}";
                    // if the queue is not specified in the config then create a dynamic queue and bind to the exchange
                    if (string.IsNullOrEmpty(_consumerConfig.QueueName))
                    {
                        var queueDeclareResult = _channel.QueueDeclare(dynamicQueue, true, true, true, null);
                        if (queueDeclareResult == null)
                        {
                            throw new IOException(Resources.TemporaryQueueCreationError);
                        }

                        _queueName = dynamicQueue;
                        _channel.QueueBind(dynamicQueue, _consumerConfig.ExchangeName, _consumerConfig.RoutingKey);
                    }
                    else
                    {
                        _queueName = _consumerConfig.QueueName;
                    }

                    _channel.BasicConsume(queue: _queueName,
                                          autoAck: false,
                                          consumer: consumer);
                    _connected = true;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"An unexpected exception occurred, error details '{ex.Message}'", ex);

                lock (_lock)
                {
                    _connected = false;
                }

                if (_channel != null)
                {
                    _channel.Dispose();
                }

                if (_connection != null)
                {
                    _connection.Dispose();
                }
            }
        }
コード例 #8
0
ファイル: QueueConsumer.cs プロジェクト: 355gts/CovidCore
        public void Consume(Func <T, ulong, string, Task> onMessage)
        {
            try
            {
                if (!_connected)
                {
                    _connection = _connectionFactory.CreateConnection(_consumerConfig.Name, _cancellationToken);

                    _channel = _connection.CreateModel();
                    _channel.BasicQos(0, _queueConfiguration.MessagePrefetchCount, false);

                    var consumer = new EventingBasicConsumer(_channel);
                    consumer.Received += async(model, ea) =>
                    {
                        var body        = ea.Body;
                        var deliveryTag = ea.DeliveryTag;
                        var routingKey  = ea.RoutingKey;

                        try
                        {
                            var message = _serializer.DeserializeObject <T>(Encoding.UTF8.GetString(body));

                            _logger.Info($"Received message");

                            if (AcknowledgementBehaviour == AcknowledgementBehaviour.PreProcess)
                            {
                                _channel.BasicAck(deliveryTag, false);
                            }

                            await onMessage(message, deliveryTag, routingKey);

                            _channel.BasicAck(deliveryTag, false);
                        }
                        catch (AlreadyClosedException ex)
                        {
                            _logger.Warn($"The connection to Rabbit was closed while processing message with deliveryTag '{deliveryTag}', error details - '{ex.Message}'.");
                        }
                        catch (Exception ex)
                        {
                            _logger.Warn($"An Exception occurred processing message with deliveryTag '{deliveryTag}', error details - '{ex.Message}'.");
                            _channel.BasicNack(deliveryTag, false, false);
                        }
                    };

                    var dynamicQueue = $"{Resources.DynamicQueuePrefix}_{Guid.NewGuid().ToString()}";
                    // if the queue is not specified in the config then create a dynamic queue and bind to the exchange
                    if (string.IsNullOrEmpty(_consumerConfig.QueueName))
                    {
                        var queueDeclareResult = _channel.QueueDeclare(dynamicQueue, true, true, true, null);
                        if (queueDeclareResult == null)
                        {
                            // TODO handle this result correctly
                        }

                        _channel.QueueBind(dynamicQueue, _consumerConfig.ExchangeName, _consumerConfig.RoutingKey);
                    }

                    _channel.BasicConsume(queue: !string.IsNullOrEmpty(_consumerConfig.QueueName) ? _consumerConfig.QueueName : dynamicQueue,
                                          autoAck: false,
                                          consumer: consumer);

                    lock (_lock)
                    {
                        _connected = true;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"An unexpected exception occurred, error details '{ex.Message}'", ex);

                lock (_lock)
                {
                    _connected = false;
                }

                if (_channel != null)
                {
                    _channel.Dispose();
                }

                if (_connection != null)
                {
                    _connection.Dispose();
                }
            }
        }
コード例 #9
0
        public void Publish(T message, IDictionary <string, object> headers, string dynamicRoutingKey)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            try
            {
                // Validate message
                string validationErrors;
                if (!_validationHelper.TryValidate(message, out validationErrors))
                {
                    throw new ValidationException(validationErrors);
                }

                // serialise object...
                string messageBody = _serializer.SerializeObject(message);

                // Determine routing key
                var routingKey = dynamicRoutingKey ?? _publisherConfig.RoutingKey;

                _logger.DebugFormat(Resources.PublishingMessageLogEntry, _publisherConfig.ExchangeName, routingKey, messageBody);

                lock (_lock)
                {
                    if (!_connected)
                    {
                        _connection = _connectionFactory.CreateConnection(_publisherConfig.Name, _cancellationToken);

                        _channel = _connection.CreateModel();

                        _connected = true;
                    }
                }

                // Create message properties
                var basicProperties = CreateBasicProperties(headers);

                _channel.BasicPublish(_publisherConfig.ExchangeName,
                                      routingKey,
                                      true,
                                      basicProperties,
                                      Encoding.UTF8.GetBytes(messageBody));

                _logger.Info($"Sent message");
            }
            catch (Exception ex)
            {
                _logger.Error($"An unexpected exception occurred, error details '{ex.Message}'", ex);

                lock (_lock)
                {
                    _connected = false;
                }

                if (_channel != null)
                {
                    _channel.Dispose();
                }

                if (_connection != null)
                {
                    _connection.Dispose();
                }
            }
        }
コード例 #10
0
 protected override void OnDestroyManager()
 {
     ConnectionHandler.Dispose();
     base.OnDestroyManager();
 }