public async Task <ChannelContainer> AcquireChannel()
        {
            if (_connection != null)
            {
                return(GetOrCreateChannel());
            }

            await _connectionLock.WaitAsync(_connectionTimeout);

            try
            {
                if (_connection?.IsOpen == false)
                {
                    ClearConnection();
                }

                var connectionFactory = new ConnectionFactory
                {
                    Uri = _uri,
                    AutomaticRecoveryEnabled = true,
                    DispatchConsumersAsync   = true,
                    RequestedHeartbeat       = _requestedHeartbeat
                };

                _connection = connectionFactory.CreateConnection(_connectionName + ":" + _channelType);
                return(GetOrCreateChannel());
            }
            finally
            {
                _connectionLock.Release();
            }
        }
Esempio n. 2
0
        private IConnection EnsureConnection()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(RabbitMQHealthCheck));
            }

            if (_connection == null)
            {
                if (_factory == null)
                {
                    _factory = new ConnectionFactory()
                    {
                        Uri = _rabbitConnectionString,
                        AutomaticRecoveryEnabled  = true,
                        UseBackgroundThreadsForIO = true,
                    };

                    if (_sslOption != null)
                    {
                        ((ConnectionFactory)_factory).Ssl = _sslOption;
                    }
                }

                _connection = _factory.CreateConnection();
            }

            return(_connection);
        }
Esempio n. 3
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            RetryPolicy retryPolicy = Policy
                                      .Handle <BrokerUnreachableException>()
                                      .WaitAndRetry(eventBusOptions.RetryCount !.Value, retryNumber => TimeSpan.FromSeconds(Math.Pow(2, retryNumber)), (exception, sleepDuration) => Console.WriteLine($"RabbitMQ connection retry, sleep duration: {sleepDuration}"));

            ConnectionFactory connectionFactory = new()
            {
                HostName = eventBusOptions.Connection,
                UserName = eventBusOptions.UserName,
                Password = eventBusOptions.Password,
                DispatchConsumersAsync = true
            };

            retryPolicy.Execute(() =>
            {
                connection = connectionFactory.CreateConnection();
            });

            channel = connection !.CreateModel();

            channel.ExchangeDeclare(exchange: eventBusOptions.BrokerName, type: ExchangeType.Direct);

            channel.QueueDeclare(queue: eventBusOptions.ClientName, durable: true, exclusive: false, autoDelete: false, arguments: null);

            channel.QueueBind(queue: eventBusOptions.ClientName, exchange: eventBusOptions.BrokerName, routingKey: nameof(UserCreatedIntegrationEvent));

            AsyncEventingBasicConsumer consumer = new(channel);

            consumer.Received += HandleIntegrationEvent;

            channel.BasicConsume(queue: eventBusOptions.ClientName, autoAck: false, consumer: consumer);

            return(Task.CompletedTask);
        }
Esempio n. 4
0
        public static IConnection Create(RabbitMQOptions options)
        {
            var theConnectionFactory = new ConnectionFactory {
                AutomaticRecoveryEnabled = true,
                HostName = options.Hostname,
                UserName = options.Username,
                Password = options.Password
            };

            RetryPolicy thePolicy = Policy
                                    .Handle <SocketException>()
                                    .Or <BrokerUnreachableException>()
                                    .WaitAndRetry(
                retryCount: ConnectionFactoryRetryCount,
                sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
                );

            IConnection?theConnection = null;

            thePolicy.Execute(() => theConnection = theConnectionFactory.CreateConnection());

            if (theConnection == null || !theConnection.IsOpen)
            {
                throw new InvalidOperationException("RabbitMQ connection could not be created.");
            }

            return(theConnection);
        }
Esempio n. 5
0
        private async Task Connect()
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            while (!socket.Connected)
            {
                try
                {
                    socket.Connect(this.host, this.port);
                }
                catch
                {
                    this.logger.LogWarning($"Connection to ExDB-Server ({this.host}:{this.port}) failed, trying again in 10 Seconds...");
                    await Task.Delay(10000).ConfigureAwait(false);
                }
            }

            this.logger.LogInformation("Connection to ExDB-Server established");

            this.connection = new Connection(SocketConnection.Create(socket), null, null, this.loggerFactory.CreateLogger <Connection>());
            this.connection.PacketReceived += this.ExDbPacketReceived;
            this.connection.Disconnected   += (sender, e) => Task.Run(async() => await this.Connect().ConfigureAwait(false));
            this.SendHello();
            await this.connection !.BeginReceive();
        }
Esempio n. 6
0
        public override Task Initialize(CancellationToken cancellationToken = default)
        {
            _connection = _connectionFactory.CreateConnection();
            _channel    = _connection.CreateModel();
            _channel.ConfirmSelect();

            return(Task.CompletedTask);
        }
 /// <summary>
 /// 实现释放资源
 /// </summary>
 /// <param name="disposing"></param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _connection?.Dispose();
     }
     _connection = default;
 }
Esempio n. 8
0
 public void Open()
 {
     _connection = _factory.CreateConnection();
     _connection.ConnectionShutdown += ConnectionConnectionShutdown;
     Inner = new ServiceInner(_connection, _rpcQueue, _prefetchCount, _logger);
     Inner.CreateChannel();
     Inner.ReceivedAsync += (_, e) => OnReceivedAsync(e);
 }
        internal static IConnection EnsureIsNotNull([NotNull] this IConnection?connection)
        {
            if (connection is null)
            {
                throw new ConnectionIsNullException();
            }

            return(connection);
        }
Esempio n. 10
0
 protected ConnectedClient CreateMultiGroupClient(
     string[]?groups        = null,
     IConnection?connection = null)
 {
     return(new ConnectedClient(
                Fixture.Create <string>(),
                connection ?? Fixture.Create <IConnection>(),
                Fixture.Create <IUpdateDetector>(),
                groups ?? Fixture.Create <IEnumerable <string> >()));
 }
Esempio n. 11
0
 protected ConnectedClient CreateSingleGroupClient(
     IConnection?connection         = null,
     IUpdateDetector?updateDetector = null)
 {
     return(new ConnectedClient(
                Fixture.Create <string>(),
                connection ?? Fixture.Create <IConnection>(),
                updateDetector ?? Fixture.Create <IUpdateDetector>(),
                Fixture.Create <string>()));
 }
Esempio n. 12
0
    public Task StartAsync(CancellationToken cancellationToken = default)
    {
        _connection = _connectionFactory.CreateConnection();
        _channel    = _connection.CreateModel();
        _channel.ConfirmSelect();

        ReadyNow();

        return(Task.CompletedTask);
    }
Esempio n. 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ChatClient" /> class.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="manager">The manager.</param>
        /// <param name="logger">The logger.</param>
        public ChatClient(IConnection connection, ChatRoomManager manager, ILogger <ChatClient> logger)
        {
            this.manager    = manager;
            this.logger     = logger;
            this.connection = connection;
            this.connection !.PacketReceived += this.ReadPacket;
            this.connection.Disconnected     += (sender, e) => this.LogOff();

            this.LastActivity = DateTime.Now;
            this.connection !.BeginReceive();
        }
Esempio n. 14
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         // dispose connection only if RabbitMQHealthCheck owns it
         if (!_disposed && _connection != null && _ownsConnection)
         {
             _connection.Dispose();
             _connection = null;
         }
         _disposed = true;
     }
 }
Esempio n. 15
0
        public void Connect(string uriString, string exchangeName, string routingKey)
        {
            ConnectionFactory factory = new ConnectionFactory
            {
                Uri = new Uri(uriString)
            };

            this.exchangeName = exchangeName;
            this.routingKey   = routingKey;

            logger.LogInformation("Connecting to {Url}", factory.Uri);

            connection  = factory.CreateConnection();
            channel     = connection.CreateModel();
            IsConnected = true;

            logger.LogInformation("Connected to {Url}", factory.Uri);

            channel.ExchangeDeclare(exchangeName, ExchangeType.Topic, true);

            var queueName = channel.QueueDeclare().QueueName;

            channel.QueueBind(queue: queueName,
                              exchange: exchangeName,
                              routingKey: routingKey);

            logger.LogInformation(" [*] {Name} ready", nameof(RabbitClient));

            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += (model, ea) =>
            {
                var body    = ea.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);

                logger.LogTrace(" [*] Received {message}", message);

                var msg = new Message()
                {
                    Content  = message,
                    Exchange = ea.Exchange,
                    Topic    = ea.RoutingKey,
                };

                OnMessageReceived?.Invoke(this, msg);
            };

            channel.BasicConsume(queue: queueName,
                                 autoAck: true,
                                 consumer: consumer);
        }
Esempio n. 16
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var(cluster, session) = await BootStrapCassandra(_configuration.For <Configuration.Cassandra>(), _logger).ConfigureAwait(false);

            _session = session;
            _cluster = cluster;
            var rabbitMqConfiguration = _configuration.For <Configuration.RabbitMQ>();

            _connection = BootStrapBroker(rabbitMqConfiguration);

            _consumer = await BootstrapConsumer(session, _connection, rabbitMqConfiguration).ConfigureAwait(false);

            _logger.Info("ServiceStarted");
        }
        public IConnection GetConnection()
        {
            lock (SLock)
            {
                if (_connection != null && _connection.IsOpen)
                {
                    return(_connection);
                }

                _connection?.Dispose();
                _connection = _connectionActivator();
                return(_connection);
            }
        }
        protected IModel GetChannel()
        {
            if (connection == null)
            {
                var factory = new ConnectionFactory {
                    HostName = _hostName,
                    DispatchConsumersAsync = true
                };

                connection = factory.CreateConnection();
                chanel     = connection.CreateModel();
            }

            return(chanel);
        }
Esempio n. 19
0
        /// <inheritdoc cref="IConnectionService.ConnectAsync" />
        public Task ConnectAsync()
        {
            _logger.LogDebug("Opening new connection to {Hostname}{VirtualHost}", _configuration.RabbitMQ.Hostname, _configuration.RabbitMQ.VirtualHost);
            _connection = new ConnectionFactory
            {
                HostName               = _configuration.RabbitMQ.Hostname,
                VirtualHost            = _configuration.RabbitMQ.VirtualHost,
                UserName               = _configuration.RabbitMQ.Username,
                Password               = _configuration.RabbitMQ.Password,
                ClientProvidedName     = _servicebusOptions.ServiceName,
                DispatchConsumersAsync = true
            }.CreateConnection();

            return(Task.CompletedTask);
        }
        protected void Connect()
        {
            var factory = new ConnectionFactory
            {
                HostName    = QueueOptions.HostName,
                VirtualHost = QueueOptions.VirtualHost,
                UserName    = QueueOptions.UserName,
                Password    = QueueOptions.Password,
                AutomaticRecoveryEnabled  = true,
                DispatchConsumersAsync    = true,
                UseBackgroundThreadsForIO = true
            };

            Connection = factory.CreateConnection($"{ServiceId}-{Name}");
        }
Esempio n. 21
0
        public void Start()
        {
            if (Status != Status.Pending)
            {
                throw new InvalidOperationException("The action is not pending activation.");
            }
            Status = Status.Running;

            IEnumerable <Message> messages = LoadMessages();

            if (_options.Shuffle)
            {
                messages = messages.Shuffle(_random);
            }
            _connection = _connectionFactory.CreateConnection();
            TryEnablePlugin();

            //Create publish tasks
            var publishTasks = new List <Task>(_options.Playback
                ? Enumerable.Range(0, 1).Select(_ => new Task(() =>
                                                              Playback(ModifyMessages(messages)), _cts.Token)) //Create 1 playback task with the modified messages
                : Enumerable.Range(0, _options.RateDetails.Multiplier).Select(_ => new Task(() =>
                                                                                            Rate(ModifyMessages(messages)),
                                                                                            _cts.Token))); //Create multiple rate tasks with the modified messages

            //Notify if error and stop when any of the tasks finish
            Task.WhenAny(publishTasks).ContinueWith(task =>
            {
                if (task.Result.IsFaulted)
                {
                    OnError(task.Result.Exception !);
                }
                else if (task.Result.IsCompleted)
                {
                    Stop();
                }
            }, _cts.Token);

            //Start all tasks
            _durationStopWatch.Start();
            _updateTick = Observable.Interval(_updateInterval).Subscribe(_ =>
            {
                _currentMetrics.Duration = _durationStopWatch.Elapsed;
                _statsSubject.OnNext(_currentMetrics);
            });
            publishTasks.ForEach(task => task.Start());
        }
Esempio n. 22
0
        public void Start()
        {
            if (Status != Status.Pending)
            {
                throw new InvalidOperationException("The action is not pending activation.");
            }
            Status      = Status.Running;
            _connection = _connectionFactory.CreateConnection();
            var channel  = _connection.CreateModel();
            var consumer = new EventingBasicConsumer(channel);

            _consumerSubscription             = Observable.FromEventPattern <BasicDeliverEventArgs>(
                handler => consumer.Received += handler,
                handler => consumer.Received -= handler)
                                                .TimeInterval()
                                                .Select(timeInterval => (ToMessage(timeInterval), timeInterval.Value.EventArgs.DeliveryTag))
                                                .Limit(_limits)
                                                .Subscribe(tuple =>
            {
                var(message, deliveryTag) = tuple;
                channel.BasicAck(deliveryTag, false);
                OnMessage(message);
            }
                                                           , Stop);
            _durationStopWatch.Restart();
            _updateTick = Observable.Interval(_updateInterval).Subscribe(_ =>
            {
                _currentMetrics.Duration = _durationStopWatch.Elapsed;
                _statsSubject.OnNext(_currentMetrics);
            });

            if (_exchange != null)
            {
                channel.QueueDeclare(_queue);
                channel.QueueBind(_queue, _exchange, _options.BindingRoutingKey);
            }

            var tag = channel.BasicConsume(consumer, _queue, false);

            _consumption = Disposable.Create(() =>
            {
                channel.BasicCancel(tag);
                channel.Close();
            });
        }
Esempio n. 23
0
        /// <summary>
        /// Start the RabbitMQ in-app server.
        /// </summary>
        public void Start()
        {
            _consumers  = new List <EventingBasicConsumer>();
            _connection = GetConnection();
            _channel    = GetChannel(_connection);

            RabbitCommonTools.DeclareExchangesAndQueueForSubscriber(_channel, _config);
            foreach (var queueDescription in _config.NetworkInfos.ServiceQueueDescriptions)
            {
                var consumer = new EventingBasicConsumer(_channel);
                consumer.Received += OnEventReceived;
                _channel.BasicConsume(
                    queue: queueDescription.QueueName,
                    autoAck: false,
                    consumer: consumer);
                _consumers.Add(consumer);
            }
        }
        protected override void OnStart(IConnection con, string conData, CancellationToken disconToken)
        {
            connection     = con;
            connectionData = conData;

            var connectUrl = UrlBuilder.BuildConnect(connection, Name, connectionData);

            if (websocket != null)
            {
                DisposeWebSocket();
            }

            // SignalR uses https, websocket4net uses wss
            connectUrl = connectUrl.Replace("http://", "ws://").Replace("https://", "wss://");

            IDictionary <string, string> cookies = new Dictionary <string, string>();

            if (connection.CookieContainer != null)
            {
                var container = connection.CookieContainer.GetCookies(new Uri(connection.Url));
                foreach (Cookie cookie in container)
                {
                    cookies.Add(cookie.Name, cookie.Value);
                }
            }

            websocket                       = new BaseSocket(log, connectUrl, cookies, connection.Headers);
            websocket.OnError              += WebSocketOnError;
            websocket.OnClose              += WebSocketOnClosed;
            websocket.OnMessage            += WebSocketOnMessageReceived;
            websocket.DataInterpreterString = interpreter;

            if (connection.Proxy != null)
            {
                var proxy = connection.Proxy.GetProxy(new Uri(connectUrl));
                websocket.SetProxy(proxy.Host, proxy.Port);
            }

            if (!websocket.Connect().Result)
            {
                TransportFailed(new Exception("Can't connect"));
            }
        }
        /// <summary>
        /// 尝试连接
        /// </summary>
        /// <returns></returns>
        public bool TryConnect()
        {
            lock (sync_locker)
            {
                Policy.Handle <SocketException>()
                .Or <BrokerUnreachableException>()
                .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => { })
                .Execute(() => _connection = _connectionFactory.CreateConnection());

                if (IsConnected)
                {
                    Connection.ConnectionShutdown += OnConnectionShutdown;
                    Connection.CallbackException  += OnCallbackException;
                    Connection.ConnectionBlocked  += OnConnectionBlocked;
                    return(true);
                }
                return(false);
            }
        }
Esempio n. 26
0
        private void OpenConnection()
        {
            if (IsConnected)
            {
                return;
            }

            _logger?.LogInformation($"RabbitMQ Client is connecting to {_connectionFactory.Uri}");

            lock (sync_root)
            {
                if (IsConnected)
                {
                    return;
                }

                var policy = Policy.Handle <SocketException>()
                             .Or <BrokerUnreachableException>()
                             .WaitAndRetry(_options.RetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                    _logger?.LogWarning(ex, "RabbitMQ Client could not connect after {TimeOut}s ({ExceptionMessage})", $"{time.TotalSeconds:n1}", ex.Message);
                }
                                           );

                policy.Execute(() =>
                {
                    _connection = _connectionFactory.CreateConnection();
                });

                if (_connection == null)
                {
                    _logger?.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened");
                    throw new QueueConnectionException("RabbitMQ connection is not created");
                }

                _connection.ConnectionShutdown += OnConnectionShutdown;
                _connection.CallbackException  += OnCallbackException;
                _connection.ConnectionBlocked  += OnConnectionBlocked;

                _logger?.LogInformation("RabbitMQ Client acquired a persistent connection to '{HostName}' and is subscribed to failure events", _connection.Endpoint.HostName);
            }
        }
Esempio n. 27
0
        public async Task TestDisconnectOnInvalidHeaderSent()
        {
            IConnection?connection = null;
            var         server     = new TcpListener(IPAddress.Any, 5000);

            server.Start();
            try
            {
                server.BeginAcceptSocket(
                    asyncResult =>
                {
                    var clientSocket     = server.EndAcceptSocket(asyncResult);
                    var socketConnection = SocketConnection.Create(clientSocket);
                    connection           = new Connection(socketConnection, new PipelinedDecryptor(socketConnection.Input), new PipelinedEncryptor(socketConnection.Output), new NullLogger <Connection>());
                }, null);

                using var client = new TcpClient("127.0.0.1", 5000);
                while (connection == null)
                {
                    Thread.Sleep(10);
                }

#pragma warning disable 4014
                connection.BeginReceive();
#pragma warning restore 4014

                var packet = new byte[22222];
                packet[0] = 0xDE;
                packet[1] = 0xAD;
                packet[2] = 0xBE;
                packet[3] = 0xAF;
                await connection.Output.WriteAsync(packet).ConfigureAwait(false);

                await Task.Delay(1000).ConfigureAwait(false);

                Assert.That(connection.Connected, Is.False);
            }
            finally
            {
                server.Stop();
            }
        }
Esempio n. 28
0
        /// <inheritdoc/>
        public void LogOff()
        {
            if (this.connection is null)
            {
                this.logger.LogDebug($"Client {this.Nickname} is already disconnected.");
                return;
            }

            this.logger.LogDebug($"Client {this.connection} is going to be disconnected.");
            if (this.room != null)
            {
                this.room.Leave(this);
                this.room = null;
            }

            this.connection?.Disconnect();
            this.connection = null;
            this.Disconnected?.Invoke(this, EventArgs.Empty);
            this.Disconnected = null;
        }
Esempio n. 29
0
        public Task StartAsync()
        {
            return(Task.Run(InitCore));

            void InitCore()
            {
                _connection = _connectionManager.CreateConnection();
                _senders    = _claptrapDesignStore
                              .Where(x => !x.IsMinion())
                              .ToDictionary(x => x.ClaptrapTypeCode, x =>
                {
                    var exchangeName = TopicHelper.GetExchangeName(x.ClaptrapTypeCode);
                    var topics       = x.EventHandlerDesigns
                                       .ToDictionary(a => a.Key, a => TopicHelper.GetRouteKey(x.ClaptrapTypeCode, a.Key));
                    using var model = _connection.CreateModel();
                    model.ExchangeDeclare(exchangeName, ExchangeType.Topic);
                    var mqSender = _mqSenderFactory.Invoke(exchangeName, topics, _connection);
                    return(mqSender);
                });
            }
        }
Esempio n. 30
0
        private IConnection ValueFactory()
        {
            var uri = _options.Value?.RabbitMQ?.Uri ?? new Uri("amqp://*****:*****@localhost:5672/%2f");
            var connectionFactory = new ConnectionFactory
            {
                DispatchConsumersAsync = true,
                Uri = uri
            };

            try
            {
                _logger.LogTrace("try to connect rabbit mq");
                var connection = connectionFactory.CreateConnection();
                _connection = connection;
                return(connection);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "failed to connect rabbit mq");
                throw;
            }
        }