예제 #1
0
        public ConnectionFactoryWrapper(IConnectionConfiguration connectionConfiguration, IClusterHostSelectionStrategy <ConnectionFactoryInfo> clusterHostSelectionStrategy)
        {
            this.clusterHostSelectionStrategy = clusterHostSelectionStrategy;
            if (connectionConfiguration == null)
            {
                throw new ArgumentNullException("connectionConfiguration");
            }
            if (!connectionConfiguration.Hosts.Any())
            {
                throw new EasyNetQException("At least one host must be defined in connectionConfiguration");
            }

            Configuration = connectionConfiguration;

            foreach (var hostConfiguration in Configuration.Hosts)
            {
                clusterHostSelectionStrategy.Add(new ConnectionFactoryInfo(new ConnectionFactory
                {
                    HostName    = hostConfiguration.Host,
                    Port        = hostConfiguration.Port,
                    VirtualHost = Configuration.VirtualHost,
                    UserName    = Configuration.UserName,
                    Password    = Configuration.Password
                }, hostConfiguration));
            }
        }
예제 #2
0
        public RabbitAdvancedBus(
            IConnectionConfiguration connectionConfiguration,
            IConnectionFactory connectionFactory,
            SerializeType serializeType,
            ISerializer serializer,
            IConsumerFactory consumerFactory,
            IEasyNetQLogger logger,
            Func <string> getCorrelationId,
            IConventions conventions,
            IMessageValidationStrategy messageValidationStrategy)
        {
            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
            Preconditions.CheckNotNull(connectionFactory, "connectionFactory");
            Preconditions.CheckNotNull(serializeType, "serializeType");
            Preconditions.CheckNotNull(serializer, "serializer");
            Preconditions.CheckNotNull(consumerFactory, "consumerFactory");
            Preconditions.CheckNotNull(logger, "logger");
            Preconditions.CheckNotNull(getCorrelationId, "getCorrelationId");
            Preconditions.CheckNotNull(conventions, "conventions");
            Preconditions.CheckNotNull(messageValidationStrategy, "messageValidationStrategy");

            this.connectionConfiguration = connectionConfiguration;
            this.serializeType           = serializeType;
            this.serializer                = serializer;
            this.consumerFactory           = consumerFactory;
            this.logger                    = logger;
            this.getCorrelationId          = getCorrelationId;
            this.conventions               = conventions;
            this.messageValidationStrategy = messageValidationStrategy;

            connection               = new PersistentConnection(connectionFactory, logger);
            connection.Connected    += OnConnected;
            connection.Disconnected += consumerFactory.ClearConsumers;
            connection.Disconnected += OnDisconnected;
        }
        // For unit testing
        internal IConnectionConfiguration GetConnection(
            string name,
            Func <string, IConnectionConfiguration> getConfigConnection,
            Func <string, bool> fileExists
            )
        {
            // First try config
            IConnectionConfiguration configuraitonConfig = getConfigConnection(name);

            if (configuraitonConfig != null)
            {
                return(configuraitonConfig);
            }

            // Then try files under the |DataDirectory| with the supported extensions
            // REVIEW: We sort because we want to process mdf before sdf (we only have 2 entries)
            foreach (var handler in _handlers.OrderBy(h => h.Key))
            {
                string fileName = Path.Combine(_dataDirectory, name + handler.Key);
                if (fileExists(fileName))
                {
                    return(handler.Value.GetConnectionConfiguration(fileName));
                }
            }

            return(null);
        }
        public RabbitMessageBus(
            IConnectionConfiguration connectionConfiguration,
            IPersistentConnection persistentConnection,
            IPersistentConnection persistentConnection1,
            ISerializer serializer,
            IConsumerFactory consumerFactory,
            IConventions conventions)
        {
            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
            Preconditions.CheckNotNull(serializer, "serializer");
            Preconditions.CheckNotNull(consumerFactory, "consumerFactory");
            Preconditions.CheckNotNull(conventions, "conventions");

            Logger           = Application.Current.LoggerProvider.GetLogger(MessageBusLoggerName);
            SerializeType    = TypeNameSerializer.Serialize;
            GetCorrelationId = CorrelationIdGenerator.GetCorrelationId;

            _connectionConfiguration = connectionConfiguration;
            Serializer           = serializer;
            Conventions          = conventions;
            ConsumerFactory      = consumerFactory;
            PersistentConnection = persistentConnection;

            PersistentConnection.Connected    += OnConnected;
            PersistentConnection.Disconnected += ConsumerFactory.ClearConsumers;
            PersistentConnection.Disconnected += OnDisconnected;
        }
예제 #5
0
        public AzureBus(
            IAzureNetQLogger logger,
            IConventions conventions,
            IRpc rpc,
            ISendReceive sendReceive,
            IAzureAdvancedBus advancedBus,
            IConnectionConfiguration connectionConfiguration,
            ISerializer serializer)
        {
            Preconditions.CheckNotNull(logger, "logger");
            Preconditions.CheckNotNull(conventions, "conventions");
            Preconditions.CheckNotNull(rpc, "rpc");
            Preconditions.CheckNotNull(sendReceive, "sendReceive");
            Preconditions.CheckNotNull(advancedBus, "advancedBus");
            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
            Preconditions.CheckNotNull(serializer, "serializer");

            this.logger                  = logger;
            this.conventions             = conventions;
            this.rpc                     = rpc;
            this.sendReceive             = sendReceive;
            this.advancedBus             = advancedBus;
            this.connectionConfiguration = connectionConfiguration;
            this.serializer              = serializer;
            this.exceptionHandler        = new ExceptionHandler(logger);
        }
예제 #6
0
파일: RabbitBus.cs 프로젝트: winhu/EasyNetQ
        public RabbitBus(
            IEasyNetQLogger logger,
            IConventions conventions,
            IAdvancedBus advancedBus,
            IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy,
            IRpc rpc,
            ISendReceive sendReceive,
            IConnectionConfiguration connectionConfiguration)
        {
            Preconditions.CheckNotNull(logger, "logger");
            Preconditions.CheckNotNull(conventions, "conventions");
            Preconditions.CheckNotNull(advancedBus, "advancedBus");
            Preconditions.CheckNotNull(publishExchangeDeclareStrategy, "publishExchangeDeclareStrategy");
            Preconditions.CheckNotNull(rpc, "rpc");
            Preconditions.CheckNotNull(sendReceive, "sendReceive");
            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");

            this.logger      = logger;
            this.conventions = conventions;
            this.advancedBus = advancedBus;
            this.publishExchangeDeclareStrategy = publishExchangeDeclareStrategy;
            this.rpc                     = rpc;
            this.sendReceive             = sendReceive;
            this.connectionConfiguration = connectionConfiguration;

            advancedBus.Connected    += OnConnected;
            advancedBus.Disconnected += OnDisconnected;
        }
예제 #7
0
        public ConnectionViewModel(
            INetworkConfiguration networkConfiguration,
            IConnectionTranslations connectionTranslations,
            IConnectionConfiguration connectionConfiguration)
        {
            _networkConfiguration   = networkConfiguration;
            ConnectionTranslations  = connectionTranslations;
            ConnectionConfiguration = connectionConfiguration;
#if DEBUG
            // For the designer
            if (!Execute.InDesignMode)
            {
                return;
            }

            LogSettings.RegisterDefaultLogger <TraceLogger>(LogLevels.Verbose);
            Log.Info().WriteLine("Running in designer");
            LoadDesignData();
#endif
            // Make sure the settings from the configuration file are used.
            HttpExtensionsGlobals.HttpSettings = _networkConfiguration;

            if (IsConfigured)
            {
                // Make the "connection"
                Task.Run(async() => await Connect());
            }
            ConnectionConfiguration.OnPropertyChanged().Subscribe(propertyChangedEventArgs =>
            {
                NotifyOfPropertyChange(nameof(IsConnected));
            });
        }
예제 #8
0
        /// <exception cref="ConnectionException">None of the provided Kafka servers are resolvable.</exception>
        public Router(
            IEnumerable <Endpoint> endpoints,
            IConnectionFactory connectionFactory             = null,
            IConnectionConfiguration connectionConfiguration = null,
            IRouterConfiguration routerConfiguration         = null,
            ILog log = null)
        {
            Log = log ?? TraceLog.Log;
            ConnectionConfiguration = connectionConfiguration ?? KafkaClient.Connections.ConnectionConfiguration.Default;
            _connectionFactory      = connectionFactory ?? new ConnectionFactory();

            var connections = new Dictionary <Endpoint, IImmutableList <IConnection> >();

            foreach (var endpoint in endpoints)
            {
                try {
                    var connection = _connectionFactory.Create(endpoint, ConnectionConfiguration, Log);
                    connections[endpoint] = ImmutableList <IConnection> .Empty.Add(connection);
                } catch (ConnectionException ex) {
                    Log.Warn(() => LogEvent.Create(ex, $"Ignoring uri that could not be connected to: {endpoint}"));
                }
            }

            _connections = connections.ToImmutableDictionary();
            if (_connections.IsEmpty)
            {
                throw new ConnectionException("None of the provided Kafka servers are resolvable.");
            }

            Configuration = routerConfiguration ?? RouterConfiguration.Default;
        }
예제 #9
0
 /// <summary>
 /// Ping a TCP peer, but don't expect an answer.
 /// </summary>
 /// <param name="remotePeer">The destination peer.</param>
 /// <param name="channelCreator">The channel creator where we create a TCP channel.</param>
 /// <param name="configuration"></param>
 /// <returns>The future response message.</returns>
 public Task <Message.Message> FireTcpAsync(PeerAddress remotePeer, ChannelCreator channelCreator,
                                            IConnectionConfiguration configuration)
 {
     return
         (CreateHandler(remotePeer, Message.Message.MessageType.RequestFf1, configuration)
          .SendTcpAsync(channelCreator));
 }
예제 #10
0
        /// <summary>
        /// Ping a TCP peer and find out how the other peer sees us.
        /// </summary>
        /// <param name="remotePeer">The destination peer.</param>
        /// <param name="channelCreator">The channel creator where we create a TCP channel.</param>
        /// <param name="configuration"></param>
        /// <param name="senderAddress"></param>
        /// <returns>The future response message.</returns>
        public Task <Message.Message> PingTcpDiscoverAsync(PeerAddress remotePeer, ChannelCreator channelCreator,
                                                           IConnectionConfiguration configuration, PeerAddress senderAddress)
        {
            var tcsResponse = CreateDiscoverHandler(remotePeer, senderAddress);

            return(new RequestHandler(tcsResponse, PeerBean, ConnectionBean, configuration).SendTcpAsync(channelCreator));
        }
        public ConnectionFactoryWrapper(IConnectionConfiguration connectionConfiguration, IClusterHostSelectionStrategy<ConnectionFactoryInfo> clusterHostSelectionStrategy)
        {
            this.clusterHostSelectionStrategy = clusterHostSelectionStrategy;
            if(connectionConfiguration == null)
            {
                throw new ArgumentNullException("connectionConfiguration");
            }
            if (!connectionConfiguration.Hosts.Any())
            {
                throw new EasyNetQException("At least one host must be defined in connectionConfiguration");
            }

            Configuration = connectionConfiguration;

            foreach (var hostConfiguration in Configuration.Hosts)
            {
                clusterHostSelectionStrategy.Add(new ConnectionFactoryInfo(new ConnectionFactory
                    {
                        HostName = hostConfiguration.Host,
                        Port = hostConfiguration.Port,
                        VirtualHost = Configuration.VirtualHost,
                        UserName = Configuration.UserName,
                        Password = Configuration.Password,
                        RequestedHeartbeat = Configuration.RequestedHeartbeat,
                        ClientProperties = ConvertToHashtable(Configuration.ClientProperties)
                    }, hostConfiguration));
            }
        }
예제 #12
0
 public ConsumerIntegrationTests()
 {
     _kafkaUri       = TestConfig.IntegrationUri;
     _config         = new ConnectionConfiguration(TimeSpan.FromSeconds(10));
     _options        = new KafkaOptions(TestConfig.IntegrationUri, _config, log: TestConfig.InfoLog);
     _consumerConfig = new ConsumerConfiguration(maxPartitionFetchBytes: DefaultMaxMessageSetSize);
 }
예제 #13
0
        /// <summary>
        /// 获取指定连接字符串名称的消息总线对象
        /// </summary>
        /// <param name="name">连接字符串名称</param>
        /// <returns>消息总线名称</returns>
        public IMessageBus GetMessageBus(string name)
        {
            Preconditions.CheckNotNull(name, "name");

            IMessageBus messageBus = null;

            if (!_messageBuses.TryGetValue(name, out messageBus))
            {
                lock (_lockObject)
                {
                    if (!_messageBuses.TryGetValue(name, out messageBus))
                    {
                        using (Application.Current.Container.BeginScope())
                        {
                            IConnectionConfiguration connectionConfiguration =
                                Application.Current.Container.Resolve <IConnectionConfiguration>(
                                    new
                            {
                                connectionString = GetConfigConnectionString(name)
                            }
                                    );
                            messageBus = Application.Current.Container.Resolve <IMessageBus>();
                        }
                        _messageBuses.Add(name, messageBus);
                    }
                }
            }
            return(messageBus);
        }
예제 #14
0
        public void GetConnectionSdfAndMdfFile_MdfFileWins()
        {
            // Arrange
            var mockSdfHandler = new Mock <MockDbFileHandler>();

            mockSdfHandler.Setup(m => m.GetConnectionConfiguration(@"DataDirectory\Bar.sdf")).Returns(new MockConnectionConfiguration("sdf connection"));
            var mockMdfHandler = new Mock <MockDbFileHandler>();

            mockMdfHandler.Setup(m => m.GetConnectionConfiguration(@"DataDirectory\Bar.mdf")).Returns(new MockConnectionConfiguration("mdf connection"));
            var handlers = new Dictionary <string, IDbFileHandler>
            {
                { ".sdf", mockSdfHandler.Object },
                { ".mdf", mockMdfHandler.Object },
            };
            var configManager = new ConfigurationManagerWrapper(handlers, "DataDirectory");
            Func <string, bool> fileExists = path => path.Equals(@"DataDirectory\Bar.mdf") ||
                                             path.Equals(@"DataDirectory\Bar.sdf");
            Func <string, IConnectionConfiguration> getFromConfig = name => null;

            // Act
            IConnectionConfiguration configuration = configManager.GetConnection("Bar", getFromConfig, fileExists);

            // Assert
            Assert.NotNull(configuration);
            Assert.Equal("mdf connection", configuration.ConnectionString);
        }
예제 #15
0
        public void Should_UsePort_From_ConnectionString()
        {
            IConnectionConfiguration connectionConfiguration = connectionStringParser.Parse("amqp=amqp://host/;port=123");


            connectionConfiguration.Port.ShouldEqual(123);
        }
예제 #16
0
 private static Database OpenConnectionInternal(IConnectionConfiguration connectionConfig)
 {
     return(OpenConnectionStringInternal(
                connectionConfig.ProviderFactory,
                connectionConfig.ConnectionString
                ));
 }
예제 #17
0
        public TcsDiscover Start()
        {
            if (_peer.IsShutdown)
            {
                return(TcsDiscoverShutdown);
            }

            if (PeerAddress == null && InetAddress != null)
            {
                PeerAddress = new PeerAddress(Number160.Zero, InetAddress, PortTcp, PortUdp);
            }
            if (PeerAddress == null)
            {
                throw new ArgumentException("Peer address or inet address required.");
            }
            if (_configuration == null)
            {
                _configuration = new DefaultConnectionConfiguration();
            }
            if (TcsDiscover == null)
            {
                TcsDiscover = new TcsDiscover();
            }

            return(Discover(PeerAddress, _configuration, TcsDiscover));
        }
예제 #18
0
        public void GetConnectionGetsConnectionFromDataDirectoryIfFileWithSupportedExtensionExists()
        {
            // Arrange
            var mockHandler = new Mock <MockDbFileHandler>();

            mockHandler
            .Setup(m => m.GetConnectionConfiguration(@"DataDirectory\Bar.foo"))
            .Returns(new MockConnectionConfiguration("some file based connection"));
            var handlers = new Dictionary <string, IDbFileHandler>
            {
                { ".foo", mockHandler.Object }
            };
            var configManager = new ConfigurationManagerWrapper(handlers, "DataDirectory");
            Func <string, bool> fileExists = path => path.Equals(@"DataDirectory\Bar.foo");
            Func <string, IConnectionConfiguration> getFromConfig = name => null;

            // Act
            IConnectionConfiguration configuration = configManager.GetConnection(
                "Bar",
                getFromConfig,
                fileExists
                );

            // Assert
            Assert.NotNull(configuration);
            Assert.Equal("some file based connection", configuration.ConnectionString);
        }
        public Dispatcher(IConnectionConfiguration connectionConfig, SubscriptionManager subscriptionManager, TimeoutProcessor timeoutProcessor)
        {
            sharedConnection = connectionConfig.CreateConnection("Dispatch");
            sharedConnection.ConnectAsync().GetAwaiter().GetResult();

            this.subscriptionManager = subscriptionManager;
            this.timeoutProcessor    = timeoutProcessor;
        }
예제 #20
0
        public void Should_AddHost_ToHosts()
        {
            IConnectionConfiguration connectionConfiguration = connectionStringParser.Parse("host=local;amqp=amqp://amqphost:1234/");

            connectionConfiguration.Hosts.Count().ShouldEqual(2);
            connectionConfiguration.Hosts.First().Host.ShouldEqual("local");
            connectionConfiguration.Hosts.Last().Host.ShouldEqual("amqphost");
        }
예제 #21
0
 public static Task <Router> CreateAsync(
     Uri serverUri,
     IConnectionFactory connectionFactory             = null,
     IConnectionConfiguration connectionConfiguration = null,
     IRouterConfiguration routerConfiguration         = null,
     ILog log = null)
 {
     return(CreateAsync(new [] { serverUri }, connectionFactory, connectionConfiguration, routerConfiguration, log));
 }
예제 #22
0
        public void Should_parse_Examples(AmqpSpecification spec)
        {
            IConnectionConfiguration connectionConfiguration = connectionStringParser.Parse("" + spec.amqpUri);

            connectionConfiguration.Port.ShouldEqual(spec.port);
            connectionConfiguration.AMQPConnectionString.ShouldEqual(spec.amqpUri);
            connectionConfiguration.Hosts.First().Host.ShouldEqual(spec.host);
            connectionConfiguration.Hosts.First().Port.ShouldEqual(spec.port);
        }
예제 #23
0
 public Router(
     Endpoint endpoint,
     IConnectionFactory connectionFactory             = null,
     IConnectionConfiguration connectionConfiguration = null,
     IRouterConfiguration routerConfiguration         = null,
     ILog log = null)
     : this(new [] { endpoint }, connectionFactory, connectionConfiguration, routerConfiguration, log)
 {
 }
 public OutboxPersister(IConnectionConfiguration config)
 {
     if (config == null)
     {
         return;
     }
     outboxConnection = config.CreateConnection("Outbox");
     outboxConnection.ConnectAsync().GetAwaiter().GetResult();
 }
        public void Should_parse_list_of_hosts_without_ports()
        {
            connectionConfiguration = parser.Parse("host=my.host.com,my.host2.com");

            Assert.AreEqual(connectionConfiguration.Hosts.First().Host, "my.host.com");
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Host, "my.host2.com");
            Assert.AreEqual(connectionConfiguration.Hosts.First().Port, 5672);
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Port, 5672);
        }
        public void Should_parse_list_of_hosts_with_single_port()
        {
            connectionConfiguration = parser.Parse("host=my.host.com,my.host2.com;port=1234");

            Assert.AreEqual(connectionConfiguration.Hosts.First().Host, "my.host.com");
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Host, "my.host2.com");
            Assert.AreEqual(connectionConfiguration.Hosts.First().Port, 1234);
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Port, 1234);
        }
예제 #27
0
        /// <summary>
        /// Ping a TCP peer and request the other peer to ping us on our public address with a
        /// fire-and-forget message.
        /// </summary>
        /// <param name="remotePeer">The destination peer.</param>
        /// <param name="channelCreator">The channel creator where we create a TCP channel.</param>
        /// <param name="configuration"></param>
        /// <returns>The future response message.</returns>
        public Task <Message.Message> PingTcpProbeAsync(PeerAddress remotePeer, ChannelCreator channelCreator,
                                                        IConnectionConfiguration configuration)
        {
            var message = CreateRequestMessage(remotePeer, Rpc.Commands.Ping.GetNr(),
                                               Message.Message.MessageType.Request3);
            var tcsResponse = new TaskCompletionSource <Message.Message>(message);

            return(new RequestHandler(tcsResponse, PeerBean, ConnectionBean, configuration).SendTcpAsync(channelCreator));
        }
        public void Should_parse_list_of_hosts_without_ports()
        {
            connectionConfiguration = parser.Parse("host=my.host.com,my.host2.com");

            Assert.AreEqual(connectionConfiguration.Hosts.First().Host, "my.host.com");
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Host, "my.host2.com");
            Assert.AreEqual(connectionConfiguration.Hosts.First().Port, 5672);
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Port, 5672);
        }
예제 #29
0
        /// <summary>
        /// Validates the <paramref name="connectionConfiguration"/> and instantiates a
        /// <c>BasicConnection</c>.
        /// </summary>
        /// <param name="connectionConfiguration">The connection configuration details.</param>
        public BasicConnection(IConnectionConfiguration connectionConfiguration)
        {
            if (!connectionConfiguration.IsValid())
            {
                throw new ArgumentException("Connection configuration is not valid");
            }

            ConnectionConfiguration = (BasicConnectionConfig)connectionConfiguration;
        }
예제 #30
0
        public RabbitAdvancedBus(
            IConnectionConfiguration connectionConfiguration,
            IConnectionFactory connectionFactory,
            SerializeType serializeType,
            ISerializer serializer,
            IConsumerFactory consumerFactory,
            IEasyNetQLogger logger,
            Func <string> getCorrelationId,
            IConventions conventions)
        {
            if (connectionConfiguration == null)
            {
                throw new ArgumentNullException("connectionConfiguration");
            }
            if (connectionFactory == null)
            {
                throw new ArgumentNullException("connectionFactory");
            }
            if (serializeType == null)
            {
                throw new ArgumentNullException("serializeType");
            }
            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }
            if (consumerFactory == null)
            {
                throw new ArgumentNullException("consumerFactory");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (getCorrelationId == null)
            {
                throw new ArgumentNullException("getCorrelationId");
            }
            if (conventions == null)
            {
                throw new ArgumentNullException("conventions");
            }

            this.connectionConfiguration = connectionConfiguration;
            this.serializeType           = serializeType;
            this.serializer       = serializer;
            this.consumerFactory  = consumerFactory;
            this.logger           = logger;
            this.getCorrelationId = getCorrelationId;
            this.conventions      = conventions;

            connection               = new PersistentConnection(connectionFactory, logger);
            connection.Connected    += OnConnected;
            connection.Disconnected += consumerFactory.ClearConsumers;
            connection.Disconnected += OnDisconnected;
        }
 public DefaultConnectionManager(IConnectionConfiguration connectionConfiguration)
 {
     this.connectionConfiguration = connectionConfiguration;
     connection = new Lazy<IEventStoreConnection>(() =>
         {
             var conn = this.connectionConfiguration.CreateConnection();
             conn.Connect();
             return conn;
         }, true);
 }
        public PersistentChannelFactory(IEasyNetQLogger logger, IConnectionConfiguration configuration, IEventBus eventBus)
        {
            Preconditions.CheckNotNull(logger, "logger");
            Preconditions.CheckNotNull(configuration, "configuration");
            Preconditions.CheckNotNull(eventBus, "eventBus");

            this.logger = logger;
            this.configuration = configuration;
            this.eventBus = eventBus;
        }
예제 #33
0
 public KafkaOptions(Uri kafkaServerUri = null,
                     IConnectionConfiguration connectionConfiguration = null,
                     IRouterConfiguration routerConfiguration         = null,
                     IConnectionFactory connectionFactory             = null,
                     IProducerConfiguration producerConfiguration     = null,
                     IConsumerConfiguration consumerConfiguration     = null,
                     ILog log = null)
     : this(ImmutableList <Uri> .Empty.AddNotNull(kafkaServerUri), connectionConfiguration, routerConfiguration, connectionFactory, producerConfiguration, consumerConfiguration, log)
 {
 }
예제 #34
0
        /// <summary>
        /// Инициализирует экземпляр ссылкой на <see cref="IConnectionConfiguration" />
        /// </summary>
        /// <param name="configuration">Провайдер конфигурации</param>
        public RedisDatabaseProvider([NotNull] IConnectionConfiguration configuration)
        {
            _connectionOptions = configuration.ThrowIfNull(nameof(configuration))
                                 .GetConnectionConfigurationOptions()
                                 .ThrowIfNull(nameof(_connectionOptions));

            _prefixKey = string.IsNullOrEmpty(_connectionOptions.Key)
        ? string.Empty
        : _connectionOptions.Key + ":";
        }
예제 #35
0
        public PublisherConfirms(IConnectionConfiguration configuration, IEasyNetQLogger logger, IEventBus eventBus) : base (eventBus)
        {
            Preconditions.CheckNotNull(configuration, "configuration");
            Preconditions.CheckNotNull(logger, "logger");
            Preconditions.CheckNotNull(eventBus, "eventBus");

            timeoutSeconds = configuration.Timeout;
            this.logger = logger;

            eventBus.Subscribe<PublishChannelCreatedEvent>(OnPublishChannelCreated);
        }
예제 #36
0
        /// <summary>
        /// Creates a request handler that can send TCP and UDP messages.
        /// </summary>
        /// <param name="tcsResponse">The future that will be called when we get an answer.</param>
        /// <param name="peerBean">The peer bean.</param>
        /// <param name="connectionBean">The connection bean.</param>
        /// <param name="configuration">The client-side connection configuration.</param>
        public RequestHandler(TaskCompletionSource<Message.Message> tcsResponse, PeerBean peerBean, ConnectionBean connectionBean, IConnectionConfiguration configuration)
        {
            _tcsResponse = tcsResponse;
            PeerBean = peerBean;
            ConnectionBean = connectionBean;
            _message = tcsResponse.Task.AsyncState as Message.Message;
            _sendMessageId = new MessageId(_message);
            IdleTcpSeconds = configuration.IdleTcpSeconds;
            IdleUdpSeconds = configuration.IdleUdpSeconds;
            ConnectionTimeoutTcpMillis = configuration.ConnectionTimeoutTcpMillis;

            //Logger.Info("Instantiated with object identity: {0}.", RuntimeHelpers.GetHashCode(this));
        }
        public void Should_parse_list_of_hosts()
        {
            connectionConfiguration = parser.Parse("host=host.one:1001,host.two:1002,host.three:1003");
            var hosts = connectionConfiguration.Hosts;

            Assert.AreEqual(hosts.Count(), 3);
            Assert.AreEqual(hosts.ElementAt(0).Host, "host.one");
            Assert.AreEqual(hosts.ElementAt(0).Port, 1001);
            Assert.AreEqual(hosts.ElementAt(1).Host, "host.two");
            Assert.AreEqual(hosts.ElementAt(1).Port, 1002);
            Assert.AreEqual(hosts.ElementAt(2).Host, "host.three");
            Assert.AreEqual(hosts.ElementAt(2).Port, 1003);
        }
예제 #38
0
        public Task<PeerAddress> Start()
        {
            if (_peer.IsShutdown)
            {
                return TaskPingShutdown;
            }

            if (_connectionConfiguration == null)
            {
                _connectionConfiguration = new DefaultConnectionConfiguration();
            }

            if (IsBroadcast)
            {
                return PingBroadcast(Port);
            }
            else
            {
                if (PeerAddress != null)
                {
                    if (IsTcpPing)
                    {
                        return Ping(PeerAddress, false);
                    }
                    else
                    {
                        return Ping(PeerAddress, true);
                    }
                }
                else if (InetAddress != null)
                {
                    if (IsTcpPing)
                    {
                        return Ping(new IPEndPoint(InetAddress, Port), Number160.Zero, false);
                    }
                    else
                    {
                        return Ping(new IPEndPoint(InetAddress, Port), Number160.Zero, true);
                    }
                }
                else if (PeerConnection != null)
                {
                    return PingPeerConnection(PeerConnection);
                }
                else
                {
                    throw new ArgumentException("Cannot ping. Peer address or inet address required.");
                }
            }
        }
        public void Should_correctly_parse_full_connection_string()
        {
            connectionConfiguration = parser.Parse(connectionString);

            Assert.AreEqual(connectionConfiguration.Hosts.First().Host, "192.168.1.1");
            Assert.AreEqual(connectionConfiguration.Hosts.First().Port, 1234);
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Host, "192.168.1.2");
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Port, 2345);
            Assert.AreEqual(connectionConfiguration.VirtualHost, "Copa");
            Assert.AreEqual(connectionConfiguration.UserName, "Copa");
            Assert.AreEqual(connectionConfiguration.Password, "abc_xyz");
            Assert.AreEqual(connectionConfiguration.Port, 12345);
            Assert.AreEqual(connectionConfiguration.RequestedHeartbeat, 3);
            Assert.AreEqual(connectionConfiguration.PrefetchCount, 2);
            Assert.AreEqual(connectionConfiguration.UsePublisherConfirms, true);
            Assert.AreEqual(connectionConfiguration.MaxWaitTimeForConfirms, new TimeSpan(2, 3, 39)); //02:03:39
            Assert.AreEqual(connectionConfiguration.RetryDelay, new TimeSpan(1, 2, 3)); //01:02:03
        }
예제 #40
0
        public InternalConsumer(
            IHandlerRunner handlerRunner, 
            IEasyNetQLogger logger, 
            IConsumerDispatcher consumerDispatcher, 
            IConventions conventions, 
            IConnectionConfiguration connectionConfiguration)
        {
            Preconditions.CheckNotNull(handlerRunner, "handlerRunner");
            Preconditions.CheckNotNull(logger, "logger");
            Preconditions.CheckNotNull(consumerDispatcher, "consumerDispatcher");
            Preconditions.CheckNotNull(conventions, "conventions");
            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");

            this.handlerRunner = handlerRunner;
            this.logger = logger;
            this.consumerDispatcher = consumerDispatcher;
            this.conventions = conventions;
            this.connectionConfiguration = connectionConfiguration;
        }
        public InternalConsumerFactory(
            IHandlerRunner handlerRunner, 
            IEasyNetQLogger logger, 
            IConventions conventions, 
            IConnectionConfiguration connectionConfiguration, 
            IConsumerDispatcherFactory consumerDispatcherFactory, 
            IEventBus eventBus)
        {
            Preconditions.CheckNotNull(handlerRunner, "handlerRunner");
            Preconditions.CheckNotNull(logger, "logger");
            Preconditions.CheckNotNull(conventions, "conventions");
            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
            Preconditions.CheckNotNull(consumerDispatcherFactory, "consumerDispatcherFactory");

            this.handlerRunner = handlerRunner;
            this.logger = logger;
            this.conventions = conventions;
            this.connectionConfiguration = connectionConfiguration;
            this.consumerDispatcherFactory = consumerDispatcherFactory;
            this.eventBus = eventBus;
        }
예제 #42
0
        public ConnectionFactoryWrapper(IConnectionConfiguration connectionConfiguration, IClusterHostSelectionStrategy<ConnectionFactoryInfo> clusterHostSelectionStrategy)
        {
            this.clusterHostSelectionStrategy = clusterHostSelectionStrategy;

            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
            Preconditions.CheckAny(connectionConfiguration.Hosts, "connectionConfiguration", "At least one host must be defined in connectionConfiguration");

            Configuration = connectionConfiguration;

            foreach (var hostConfiguration in Configuration.Hosts)
            {
                var connectionFactory = new ConnectionFactory();
                if (connectionConfiguration.AMQPConnectionString != null)
                {
                    connectionFactory.uri = connectionConfiguration.AMQPConnectionString;
                }

                connectionFactory.HostName = hostConfiguration.Host;

                if(connectionFactory.VirtualHost == "/")
                    connectionFactory.VirtualHost = Configuration.VirtualHost;

                if(connectionFactory.UserName == "guest")
                    connectionFactory.UserName = Configuration.UserName;

                if(connectionFactory.Password == "guest")
                    connectionFactory.Password = Configuration.Password;

                if (connectionFactory.Port == -1)
                    connectionFactory.Port = hostConfiguration.Port;

                if (Configuration.Ssl.Enabled)
                    connectionFactory.Ssl = Configuration.Ssl;

                connectionFactory.RequestedHeartbeat = Configuration.RequestedHeartbeat;
                connectionFactory.ClientProperties = ConvertToHashtable(Configuration.ClientProperties);
                clusterHostSelectionStrategy.Add(new ConnectionFactoryInfo(connectionFactory, hostConfiguration));
            }
        }
예제 #43
0
 public Task<Message.Message> SendAsync(PeerAddress remotePeer, BroadcastBuilder broadcastBuilder,
     ChannelCreator channelCreator, IConnectionConfiguration configuration)
 {
     var message = CreateRequestMessage(remotePeer, Rpc.Commands.Broadcast.GetNr(),
         Message.Message.MessageType.RequestFf1);
     message.SetIntValue(broadcastBuilder.HopCounter);
     message.SetKey(broadcastBuilder.MessageKey);
     if (broadcastBuilder.DataMap != null)
     {
         message.SetDataMap(new DataMap(broadcastBuilder.DataMap));
     }
     var tcsResponse = new TaskCompletionSource<Message.Message>(message);
     var requestHandler = new RequestHandler(tcsResponse, PeerBean, ConnectionBean, configuration);
     if (!broadcastBuilder.IsUdp)
     {
         return requestHandler.SendTcpAsync(channelCreator);
     }
     else
     {
         return requestHandler.FireAndForgetUdpAsync(channelCreator);
     }
 }
예제 #44
0
        public ConnectionFactoryWrapper(IConnectionConfiguration connectionConfiguration, IClusterHostSelectionStrategy<ConnectionFactoryInfo> clusterHostSelectionStrategy)
        {
            this.clusterHostSelectionStrategy = clusterHostSelectionStrategy;

            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
            Preconditions.CheckAny(connectionConfiguration.Hosts, "connectionConfiguration", "At least one host must be defined in connectionConfiguration");

            Configuration = connectionConfiguration;

            foreach (var hostConfiguration in Configuration.Hosts)
            {
                clusterHostSelectionStrategy.Add(new ConnectionFactoryInfo(new ConnectionFactory
                    {
                        HostName = hostConfiguration.Host,
                        Port = hostConfiguration.Port,
                        VirtualHost = Configuration.VirtualHost,
                        UserName = Configuration.UserName,
                        Password = Configuration.Password,
                        RequestedHeartbeat = Configuration.RequestedHeartbeat,
                        ClientProperties = ConvertToHashtable(Configuration.ClientProperties)
                    }, hostConfiguration));
            }
        }
예제 #45
0
        /// <summary>
        /// .NET-specific: Used for DistributedRouting only.
        /// </summary>
        internal TaskCompletionSource<Message.Message> CloseNeighborsTcs(PeerAddress remotePeer, SearchValues searchValues, Message.Message.MessageType type,
            ChannelCreator channelCreator, IConnectionConfiguration configuration)
        {
            var message = CreateRequestMessage(remotePeer, Rpc.Commands.Neighbor.GetNr(), type);
            if (!message.IsRequest())
            {
                throw new ArgumentException("The type must be a request.");
            }
            message.SetKey(searchValues.LocationKey);
            message.SetKey(searchValues.DomainKey ?? Number160.Zero);

            if (searchValues.From != null && searchValues.To != null)
            {
                ICollection<Number640> collection = new List<Number640>();
                collection.Add(searchValues.From);
                collection.Add(searchValues.To);
                var keyCollection = new KeyCollection(collection);
                message.SetKeyCollection(keyCollection);
            }
            else
            {
                if (searchValues.ContentKey != null)
                {
                    message.SetKey(searchValues.ContentKey);
                }
                if (searchValues.KeyBloomFilter != null)
                {
                    message.SetBloomFilter(searchValues.KeyBloomFilter);
                }
                if (searchValues.ContentBloomFilter != null)
                {
                    message.SetBloomFilter(searchValues.ContentBloomFilter);
                }
            }
            return Send(message, configuration, channelCreator);
        }
예제 #46
0
        /// <summary>
        /// Needs 3 connections. Cleans up channel creator, which means they will be released.
        /// </summary>
        /// <param name="tcsDiscover"></param>
        /// <param name="peerAddress"></param>
        /// <param name="cc"></param>
        /// <param name="configuration"></param>
        private void Discover(TcsDiscover tcsDiscover, PeerAddress peerAddress, ChannelCreator cc,
            IConnectionConfiguration configuration)
        {
            _peer.PingRpc.AddPeerReachableListener(new DiscoverPeerReachableListener(tcsDiscover));

            var taskResponseTcp = _peer.PingRpc.PingTcpDiscoverAsync(peerAddress, cc, configuration, SenderAddress);
            taskResponseTcp.ContinueWith(taskResponse =>
            {
                var serverAddress = _peer.PeerBean.ServerPeerAddress;
                if (!taskResponse.IsFaulted)
                {
                    var tmp = taskResponseTcp.Result.NeighborsSet(0).Neighbors;
                    tcsDiscover.SetReporter(taskResponseTcp.Result.Sender);
                    if (tmp.Count == 1)
                    {
                        var seenAs = tmp.First();
                        Logger.Info("This peer is seen as {0} by peer {1}. This peer sees itself as {2}.", seenAs, peerAddress, _peer.PeerAddress.InetAddress);
                        if (!_peer.PeerAddress.InetAddress.Equals(seenAs.InetAddress))
                        {
                            // check if we have this interface on that we can listen to
                            var bindings = new Bindings().AddAddress(seenAs.InetAddress);
                            var status = DiscoverNetworks.DiscoverInterfaces(bindings);
                            Logger.Info("2nd interface discovery: {0}.", status);
                            if (bindings.FoundAddresses.Count > 0
                                && bindings.FoundAddresses.Contains(seenAs.InetAddress))
                            {
                                serverAddress = serverAddress.ChangeAddress(seenAs.InetAddress);
                                _peer.PeerBean.SetServerPeerAddress(serverAddress);
                                Logger.Info("This peer had the wrong interface. Changed it to {0}.", serverAddress);
                            }
                            else
                            {
                                // now we know our internal IP, where we receive packets
                                var ports =
                                    _peer.ConnectionBean.ChannelServer.ChannelServerConfiguration.PortsForwarding;
                                if (ports.IsManualPort)
                                {
                                    serverAddress = serverAddress.ChangePorts(ports.TcpPort, ports.UdpPort);
                                    serverAddress = serverAddress.ChangeAddress(seenAs.InetAddress);
                                    _peer.PeerBean.SetServerPeerAddress(serverAddress);
                                    Logger.Info("This peer had manual ports. Changed it to {0}.", serverAddress);
                                }
                                else
                                {
                                    // we need to find a relay, because there is a NAT in the way
                                    tcsDiscover.SetExternalHost(
                                        "We are most likely behind a NAT. Try to UPNP, NAT-PMP or relay " + peerAddress, taskResponseTcp.Result.Recipient.InetAddress, seenAs.InetAddress);
                                    return;
                                }
                            }
                        }
                        // else -> we announce exactly how the other peer sees us
                        var taskResponse1 = _peer.PingRpc.PingTcpProbeAsync(peerAddress, cc, configuration);
                        taskResponse1.ContinueWith(tr1 =>
                        {
                            if (tr1.IsFaulted)
                            {
                                tcsDiscover.SetException(new TaskFailedException("TcsDiscover (2): We need at least the TCP connection.", tr1));
                            }
                        });
                        
                        var taskResponse2 = _peer.PingRpc.PingUdpProbeAsync(peerAddress, cc, configuration);
                        taskResponse2.ContinueWith(tr2 =>
                        {
                            if (tr2.IsFaulted)
                            {
                                Logger.Warn("TcsDiscover (2): UDP failed connection.");
                            }
                        });

                        // from here we probe, set the timeout here
                        tcsDiscover.Timeout(serverAddress, _peer.ConnectionBean.Timer, DiscoverTimeoutSec);
                        return;
                    }
                    tcsDiscover.SetException(new TaskFailedException(String.Format("Peer {0} did not report our IP address.", peerAddress)));
                }
                else
                {
                    tcsDiscover.SetException(new TaskFailedException("TcsDiscover (1): We need at least the TCP connection.", taskResponse));
                }
            });
        }
예제 #47
0
        /// <summary>
        /// Discover attempts to find the external IP address of this peer. This is done by first trying to set
        /// UPNP with port forwarding (gives us the external address), query UPNP for the external address, and
        /// pinging a well-known peer. The fallback is NAT-PMP.
        /// </summary>
        /// <param name="peerAddress">The peer address. Since pings are used the peer ID can be Number160.Zero.</param>
        /// <param name="configuration"></param>
        /// <param name="tcsDiscover"></param>
        /// <returns>The future discover. This holds also the real ID of the peer we send the discover request.</returns>
        private TcsDiscover Discover(PeerAddress peerAddress, IConnectionConfiguration configuration,
            TcsDiscover tcsDiscover)
        {
            var taskCc = _peer.ConnectionBean.Reservation.CreateAsync(1, 2);
            Utils.Utils.AddReleaseListener(taskCc, TcsDiscover.Task);
            taskCc.ContinueWith(tcc =>
            {
                if (!tcc.IsFaulted)
                {
                    Discover(tcsDiscover, peerAddress, tcc.Result, configuration);
                }
                else
                {
                    tcsDiscover.SetException(tcc.TryGetException());
                }
            });

            return tcsDiscover;
        }
예제 #48
0
        public TcsDiscover Start()
        {
            if (_peer.IsShutdown)
            {
                return TcsDiscoverShutdown;
            }

            if (PeerAddress == null && InetAddress != null)
            {
                PeerAddress = new PeerAddress(Number160.Zero, InetAddress, PortTcp, PortUdp);
            }
            if (PeerAddress == null)
            {
                throw new ArgumentException("Peer address or inet address required.");
            }
            if (_configuration == null)
            {
                _configuration = new DefaultConnectionConfiguration();
            }
            if (TcsDiscover == null)
            {
                TcsDiscover = new TcsDiscover();
            }

            return Discover(PeerAddress, _configuration, TcsDiscover);
        }
 public void Should_parse_the_username()
 {
     connectionConfiguration = parser.Parse("host=localhost;username=test");
     Assert.AreEqual("test", connectionConfiguration.UserName);
 }
 public void AddConnection(string name, IConnectionConfiguration configuration)
 {
     _connectionStrings.Add(name, configuration);
 }
 public void Should_parse_the_hostname()
 {
     connectionConfiguration = parser.Parse("host=myHost");
     Assert.AreEqual("myHost", connectionConfiguration.Hosts.First().Host);
 }
 public void SetUp()
 {
     connectionString = new ConnectionStringParser().Parse(connectionStringValue);
     defaults = new ConnectionStringParser().Parse("host=localhost");
 }
예제 #53
0
 public static IPublisher CreatePublisher(IConnectionConfiguration configuration, IEasyNetQLogger logger, IEventBus eventBus)
 {
     return configuration.PublisherConfirms
                ? (IPublisher) new PublisherConfirms(configuration, logger, eventBus)
                : new PublisherBasic(eventBus);
 }
 public HomeAccountantSqlDataRepository(IConnectionConfiguration config)
 {
     this.context = new HomeAccountantContext(config.HomeAccountantConnectionString);
 }
 public RabbitMqConnectionManager(IConnectionFactory connectionFactory,IConnectionConfiguration connectionConfiguration)
 {
     this.connectionFactory = connectionFactory;
     this.connectionConfiguration = connectionConfiguration;
 }
        public void Should_parse_list_of_hosts_with_single_port()
        {
            connectionConfiguration = parser.Parse("host=my.host.com,my.host2.com;port=1234");

            Assert.AreEqual(connectionConfiguration.Hosts.First().Host, "my.host.com");
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Host, "my.host2.com");
            Assert.AreEqual(connectionConfiguration.Hosts.First().Port, 1234);
            Assert.AreEqual(connectionConfiguration.Hosts.Last().Port, 1234);
        }
예제 #57
0
        /// <summary>
        /// Creates a new instance of RabbitBus
        /// </summary>
        /// <param name="connectionConfiguration">
        /// An IConnectionConfiguration instance.
        /// </param>
        /// <param name="registerServices">
        /// Override default services. For example, to override the default IEasyNetQLogger:
        /// RabbitHutch.CreateBus("host=localhost", x => x.Register&lt;IEasyNetQLogger&gt;(_ => myLogger));
        /// </param>
        /// <returns></returns>
        public static IBus CreateBus(IConnectionConfiguration connectionConfiguration, Action<IServiceRegister> registerServices)
        {
            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
            Preconditions.CheckNotNull(registerServices, "registerServices");

            var container = createContainerInternal();
            if (container == null)
            {
                throw new EasyNetQException("Could not create container. " + 
                    "Have you called SetContainerFactory(...) with a function that returns null?");
            }

            registerServices(container);
            container.Register(_ => connectionConfiguration);
            ComponentRegistration.RegisterServices(container);

            return container.Resolve<IBus>();
        }
 public void Should_parse_the_virtual_hostname()
 {
     connectionConfiguration = parser.Parse("host=localhost;virtualHost=myVirtualHost");
     Assert.AreEqual("myVirtualHost", connectionConfiguration.VirtualHost);
 }
예제 #59
0
        /// <summary>
        /// Creates a new instance of RabbitBus
        /// </summary>
        /// <param name="connectionConfiguration">
        /// An IConnectionConfiguration instance.
        /// </param>
        /// <param name="registerServices">
        /// Override default services. For example, to override the default IEasyNetQLogger:
        /// RabbitHutch.CreateBus("host=localhost", x => x.Register&lt;IEasyNetQLogger&gt;(_ => myLogger));
        /// </param>
        /// <returns></returns>
        public static IBus CreateBus(IConnectionConfiguration connectionConfiguration, Action<IServiceRegister> registerServices)
        {
            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
            Preconditions.CheckNotNull(registerServices, "registerServices");

            Action<IServiceRegister> registerServices2 = x =>
            {
                x.Register(_ => connectionConfiguration);
                registerServices(x);
            };

            var serviceProvider = ComponentRegistration.CreateServiceProvider(registerServices2);

            return serviceProvider.Resolve<IBus>();
        }
예제 #60
0
 private static Database OpenConnectionInternal(IConnectionConfiguration connectionConfig)
 {
     return OpenConnectionStringInternal(connectionConfig.ProviderFactory, connectionConfig.ConnectionString);
 }