Ejemplo n.º 1
0
 public NmsConnection(IConnectionFactory connectionFactory, Apache.NMS.AcknowledgementMode acknowledgementMode, NmsCredentials credentials)
 {
     this.connection = (credentials == null)
         ? connectionFactory.CreateConnection()
         : connectionFactory.CreateConnection(credentials.Username, credentials.Password);
     this.acknowledgementMode = acknowledgementMode;
     this.id = idCounter++;
     this.WireUpEvents();
 }
Ejemplo n.º 2
0
        public ChannelFactory(RawRabbitConfiguration config, IConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
            _accessDictionary = new ConcurrentDictionary<IModel, DateTime>();
            _config = config;
            _threadChannels = new ThreadLocal<IModel>(true);

            try
            {
                _logger.LogDebug("Connecting to primary host.");
                _connection = _connectionFactory.CreateConnection(_config.Hostnames);
                _logger.LogInformation("Successfully established connection.");
            }
            catch (BrokerUnreachableException e)
            {
                _logger.LogError("Unable to connect to broker", e);
                throw e.InnerException;
            }
            _closeTimer = new System.Threading.Timer(state =>
            {
                var enumerator = _accessDictionary.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    if (DateTime.Now - enumerator.Current.Value > _config.RequestTimeout)
                    {
                        DateTime lastUsed;
                        if (_accessDictionary.TryRemove(enumerator.Current.Key, out lastUsed))
                        {
                            _logger.LogInformation($"Channel {enumerator.Current.Key.ChannelNumber} was last used {lastUsed}. Closing...");
                            enumerator.Current.Key.Close();
                        }
                    }
                }
            }, null, _config.RequestTimeout, _config.RequestTimeout);
        }
Ejemplo n.º 3
0
        private void CreateMocks()
        {
            mockConnectionFactory = (IConnectionFactory) mocks.CreateMock(typeof (IConnectionFactory));
            mockConnection = (IConnection) mocks.CreateMock(typeof (IConnection));
            mockSession = (ISession) mocks.CreateMock(typeof (ISession));

            TIBCO.EMS.Queue queue = new TIBCO.EMS.Queue("test"); //(Queue) mocks.CreateMock(typeof (Queue));

            Expect.Call(mockConnectionFactory.CreateConnection()).Return(mockConnection).Repeat.Once();
            if (UseTransactedTemplate)
            {
                Expect.Call(mockConnection.CreateSession(true, Session.SESSION_TRANSACTED)).Return(mockSession).Repeat.
                    Once();
            }
            else
            {
                Expect.Call(mockConnection.CreateSession(false, Session.AUTO_ACKNOWLEDGE)).Return(mockSession).
                    Repeat.
                    Once();
            }
            Expect.Call(mockSession.Transacted).Return(true);

            mockDestinationResolver =
                (IDestinationResolver) mocks.CreateMock(typeof (IDestinationResolver));
            mockDestinationResolver.ResolveDestinationName(mockSession, "testDestination", false);
            LastCall.Return(queue).Repeat.Any();
        }
 public void SetUp()
 {
     connectionFactory = new ConnectionFactory("tcp://localhost:61616", GetType().Name);
     connection = connectionFactory.CreateConnection();
     connection.Start();
     session = connection.CreateSession();
 }
Ejemplo n.º 5
0
        private void CreateMocks()
        {
            mockConnectionFactory = (IConnectionFactory) mocks.CreateMock(typeof (IConnectionFactory));
            mockConnection = (IConnection) mocks.CreateMock(typeof (IConnection));
            mockSession = (ISession) mocks.CreateMock(typeof (ISession));

            IQueue queue = (IQueue) mocks.CreateMock(typeof (IQueue));

            Expect.Call(mockConnectionFactory.CreateConnection()).Return(mockConnection).Repeat.Once();
            if (UseTransactedTemplate)
            {
                Expect.Call(mockConnection.CreateSession(AcknowledgementMode.Transactional)).Return(mockSession).Repeat.
                    Once();
            }
            else
            {
                Expect.Call(mockConnection.CreateSession(AcknowledgementMode.AutoAcknowledge)).Return(mockSession).
                    Repeat.
                    Once();
            }
            Expect.Call(mockSession.Transacted).Return(true);

            mockDestinationResolver =
                (IDestinationResolver) mocks.CreateMock(typeof (IDestinationResolver));
            mockDestinationResolver.ResolveDestinationName(mockSession, "testDestination", false);
            LastCall.Return(queue).Repeat.Any();
        }
Ejemplo n.º 6
0
        public Queue(MsgDeliveryMode mode = MsgDeliveryMode.NonPersistent)
        {
            Uri msgQueue = new Uri("activemq:tcp://localhost:61616");

            _factory = new ConnectionFactory(msgQueue);
            try
            {
                _connection = _factory.CreateConnection();
            }
            catch (NMSConnectionException ex)
            {
                Log.FatalException("Error connecting to MQ server", ex);
                throw;
            }
            // TODO check _connection for null
            _connection.RequestTimeout = TimeSpan.FromSeconds(60);
            Session = _connection.CreateSession();

            // TODO need to find out if queue exists.
            // It creates a new queue if it doesn't exist.
            _destination = Session.GetDestination("queue://TwitterSearchStream");
            _consumer = Session.CreateConsumer(_destination);

            _producer = Session.CreateProducer(_destination);
            _producer.RequestTimeout = TimeSpan.FromSeconds(60);
            _producer.DeliveryMode = mode;

            _connection.Start();

            _connection.ExceptionListener += _connection_ExceptionListener;
            _connection.ConnectionInterruptedListener += _connection_ConnectionInterruptedListener;
        }
Ejemplo n.º 7
0
 public MessageTransporter()
 {
     _connectionFactory = new Apache.NMS.Stomp.ConnectionFactory("tcp://0.0.0.0:61613");
     _connection = _connectionFactory.CreateConnection();
     _session = _connection.CreateSession();
     _destination = SessionUtil.GetDestination(_session, "queue://testingQueue");
     _messageProducer = _session.CreateProducer(_destination);
     _messageConsumer = _session.CreateConsumer(_destination);
 }
Ejemplo n.º 8
0
        protected void TryCreateConnectionFactory(object stateInfo)
        {
            if (Connection != null) Connection.Dispose();
            Connection = null;

            if (stateInfo != null)
            {
                Log.Information("Retrying connection");
                var autoEvent = (AutoResetEvent)stateInfo;
                autoEvent.Set();
            }
            var tempHostNames = hostNames;
            //hostNames.Shuffle();
            foreach (var hostName in tempHostNames)
            {
                try
                {
                    factory = new ConnectionFactory
                    {
                        HostName = hostName,
                        UserName = userName,
                        Password = password,
                        NetworkRecoveryInterval = TimeSpan.FromMilliseconds(timeout),
                        AutomaticRecoveryEnabled = automaticRecoveryEnabled,
                        RequestedHeartbeat = (ushort) heartbeat,
                        RequestedConnectionTimeout = 60000
                    };
                    Connection = factory.CreateConnection();
                    Log.Information(
                        "Connection heartbeat is configured to {0} seconds,  and the connection has returned a value of {1} seconds",
                        heartbeat, Connection.Heartbeat);
                    Connection.ConnectionShutdown += connection_ConnectionShutdown;
                    WaitingToConnect = false;
                    break;
                }
                catch (SocketException se)
                {
                    Log.Error(se, "RabbitMq: TryCreateConnectionFactory has an Error creating connection to host {0}",
                        hostName);
                }
                catch (BrokerUnreachableException be)
                {
                    Log.Error(be, "RabbitMq: TryCreateConnectionFactory Cannot reach broker for host {0}", hostName);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "RabbitMq: TryCreateConnectionFactory has an Error with {0} - {1}", hostName,
                        ex.Message);
                }
                finally
                {
                    if (Connection != null) Connection.Close();
                }
            }
            if (Connection == null) StartTryToConnect();
        }
Ejemplo n.º 9
0
 private void Connect()
 {
     factory = XmsUtilities.CreateConnectionFactory(destination);
     connection = factory.CreateConnection();
     connection.ExceptionListener += OnError;
     session = connection.CreateSession(transactional, AcknowledgeMode.AutoAcknowledge);
     queue = session.CreateQueue(destination.Queue);
     queue.SetIntProperty(XMSC.DELIVERY_MODE, XMSC.DELIVERY_PERSISTENT);
     producer = session.CreateProducer(queue);
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Configurate the Connection
        /// </summary>
        /// <param name="destination">Destionation</param>
        private void Configure(string destination)
        {
            Destination dest = new Destination(destination);

            Uri connectionUri = new Uri(dest.Host);
            factory = new Apache.NMS.ActiveMQ.ConnectionFactory(connectionUri);
            connection = factory.CreateConnection();
            session = connection.CreateSession();
            connection.Start();
            this.destination = session.GetDestination(dest.Queue);
        }
Ejemplo n.º 11
0
        private void Configure(string destination)
        {
            Destination dest = new Destination(destination);

            Uri connectionUri = new Uri(dest.Host);
            _factory = new NMSConnectionFactory(connectionUri);
            _connection = _factory.CreateConnection();
            _session = _connection.CreateSession();
            _connection.Start();
            _destination = _session.GetDestination(dest.Queue);
        }
Ejemplo n.º 12
0
        public Master(IUserService service)
        {
            DownloadUsers = new DownloadUsers(service);

            Factory = new NMSConnectionFactory("tcp://localhost:61616");
            Connection = Factory.CreateConnection();
            Connection.Start();
            Session = Connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            Destination = SessionUtil.GetDestination(Session, "Users");
            Receiver = Session.CreateConsumer(Destination);
        }
Ejemplo n.º 13
0
        public void SetUp()
        {
            connectionFactory = new ConnectionFactory(BROKER, CLIENT_ID);
            connection = connectionFactory.CreateConnection();
            connection.Start();
            session = connection.CreateSession();

            subscriber = new TopicSubscriber(session, TOPIC_NAME);
            subscriber.Start(CONSUMER_ID);
            subscriber.OnMessageReceived +=
                message => Console.WriteLine("Recieving message=>{0}", message);
        }
Ejemplo n.º 14
0
 public SingleNodeBroker(BrokerConfiguration config = null)
 {
     config = config ?? BrokerConfiguration.Local;
     _factory = new ConnectionFactory
     {
         HostName = config.Hostname,
         VirtualHost = config.VirtualHost,
         Password = config.Password,
         UserName = config.Username
     };
     _connection = _factory.CreateConnection();
 }
Ejemplo n.º 15
0
        public void Setup()
        {
            _endPoint = new DnsEndPoint("localhost", 27017);
            _connection = new MockConnection();
            _connectionFactory = Substitute.For<IConnectionFactory>();
            _connectionFactory.CreateConnection(null, null)
                .ReturnsForAnyArgs(_connection);

            _capturedEvents = new EventCapturer();

            _serverId = new ServerId(new ClusterId(), _endPoint);
            _subject = new ServerMonitor(_serverId, _endPoint, _connectionFactory, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan, _capturedEvents);
        }
Ejemplo n.º 16
0
 public void Connect()
 {
     log.Debug("New physical producer created. About to connect.");
     factory = XmsUtilities.CreateConnectionFactory(address);
     connection = factory.CreateConnection();
     connection.ExceptionListener += OnError;
     session = connection.CreateSession(transactional, AcknowledgeMode.AutoAcknowledge);
     queue = session.CreateQueue(address.Queue);
     queue.SetIntProperty(XMSC.DELIVERY_MODE, XMSC.DELIVERY_PERSISTENT);
     producer = session.CreateProducer(queue);
     connected = true;
     log.Debug("New physical producer successfully connected.");
 }
Ejemplo n.º 17
0
 public void Connect()
 {
     factory = XmsUtilities.CreateConnectionFactory(address);
     connection = factory.CreateConnection();
     connection.ExceptionListener += OnError;
     session = connection.CreateSession(transactional, AcknowledgeMode.AutoAcknowledge);
     queue = session.CreateQueue(address.Queue);
     queue.SetIntProperty(XMSC.DELIVERY_MODE,
                          transactional ? XMSC.DELIVERY_PERSISTENT : XMSC.DELIVERY_NOT_PERSISTENT);
     consumer = session.CreateConsumer(queue);
     connection.Start();
     connected = true;
 }
Ejemplo n.º 18
0
        public Stomp(bool durable)
        {
            _connectionFactory = new ConnectionFactory("tcp://localhost:61613");
            _connection = _connectionFactory.CreateConnection();
            _connection.ClientId = "13AC0CF8-65FE-4638-8B85-62210DD89BEE";
            _connection.Start();
            _session = _connection.CreateSession();

            var topic = _session.GetQueue("exampleQueue");

            _producer = _session.CreateProducer(topic);
            _producer.DeliveryMode = durable ? MsgDeliveryMode.Persistent : MsgDeliveryMode.NonPersistent;

            _consumer = _session.CreateConsumer(topic);
        }
Ejemplo n.º 19
0
        public void Setup()
        {
            connectionFactory = new ConnectionFactory(BROKER, CLIENT_ID);
            connection = connectionFactory.CreateConnection();
            connection.Start();
            session = connection.CreateSession();

            for (int i = 0; i < 100; i++)
            {
                var receiver = new QueueReceiver(session, QUEUE_NAME);
                receiver.OnMessageRecieved += (message => Console.WriteLine(message));
                receiver.Start(String.Format("Receiver#{0}", i));
                receivers.Add(receiver);
            }
        }
Ejemplo n.º 20
0
        public ManagedConnection(Uri uri)
        {
            if (uri == null) throw new ArgumentNullException("uri");

            var managedConnectionIdBuilder = new UriBuilder(uri)
            {
                // Sanitize credentials
                UserName = "",
                Password = ""
            };
            _managedConnectionId = managedConnectionIdBuilder.Uri.ToString();
            _connectionFactory = new ConnectionFactory {Uri = uri.ToString()};

            Log.InfoFormat("Establishing managed connection to {0}...", _managedConnectionId);
            _connection = _connectionFactory.CreateConnection();
        }
Ejemplo n.º 21
0
        public ChannelFactory(RawRabbitConfiguration config, IConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;

            _config = config;
            _threadChannels = new ThreadLocal<IModel>(true);

            try
            {
                _logger.LogDebug("Connecting to primary host.");
                _connection = _connectionFactory.CreateConnection(_config.Hostnames);
                _logger.LogInformation("Successfully established connection.");
            }
            catch (BrokerUnreachableException e)
            {
                _logger.LogError("Unable to connect to broker", e);
                throw e.InnerException;
            }
        }
Ejemplo n.º 22
0
        public ChannelFactory(IConnectionFactory connectionFactory, RawRabbitConfiguration config, ChannelFactoryConfiguration channelConfig)
        {
            try
            {
                _connection = connectionFactory.CreateConnection(config.Hostnames);
            }
            catch (BrokerUnreachableException e)
            {
                _logger.LogError("Unable to connect to broker", e);
                throw e.InnerException;
            }
            _connectionFactory = connectionFactory;
            _config = config;
            _channelConfig = channelConfig;
            _requestQueue = new ConcurrentQueue<TaskCompletionSource<IModel>>();
            _channels = new LinkedList<IModel>();

            Initialize();
        }
Ejemplo n.º 23
0
        public void InitForm()
        {
            try
            {

                factory = new ConnectionFactory(connectUri);
                connection = factory.CreateConnection("sempra.ops.gs.service", "sempra");
                connection.ExceptionListener += new ExceptionListener(OnException);
                connection.Start();

                session = connection.CreateSession();
                
                //destination = SessionUtil.GetDestination(session, "topic://sempra.ops.opsTracking.summary.update" + MAX_INACTIVITY_DURATION);

                //This is the process that registers the subscriber on the server
                //consumer = session.CreateConsumer(destination);
                ////////////////////////////////////////

                //producer = session.CreateProducer(destination);
                //consumer.Listener += new MessageListener(OnMessage);
                
                topicSubscriber = new TopicSubscriber(session, TOPIC_NAME);
                topicSubscriber.OnMessageReceived += new MessageListener(OnMessage);
                topicSubscriber.Start(CONSUMER_ID);

                ////////////////////////////////////////
                //_connectionFactory = new ConnectionFactory(_connectUri, CLIENT_ID);
                //_connection = _connectionFactory.CreateConnection(Properties.Settings.Default.MessageServerUserId, Properties.Settings.Default.MessageServerPassword);
                //_connection.ExceptionListener += new ExceptionListener(OnException);
                //_connection.Start();
                //_session = _connection.CreateSession();
                //_session = _connection.CreateSession(AcknowledgementMode.AutoAcknowledge);

                //_topicSubscriber = new TopicSubscriber(_session, TOPIC_NAME);
                //_topicSubscriber.Start(CONSUMER_ID);
                //_topicSubscriber.OnMessageReceived += new MessageListener(OnMessage);
            }
            catch (Exception error)
            {
                MessageBox.Show("Error:" + error.Message);
            }
        }
        public void Setup()
        {
            _clusterId = new ClusterId();
            _clusterConnectionMode = ClusterConnectionMode.Standalone;
            _connectionPool = Substitute.For<IConnectionPool>();
            _connectionPoolFactory = Substitute.For<IConnectionPoolFactory>();
            _connectionPoolFactory.CreateConnectionPool(null, null)
                .ReturnsForAnyArgs(_connectionPool);

            _endPoint = new DnsEndPoint("localhost", 27017);
            _heartbeatConnection = new MockConnection();
            _heartbeatConnectionFactory = Substitute.For<IConnectionFactory>();
            _heartbeatConnectionFactory.CreateConnection(null, null)
                .ReturnsForAnyArgs(_heartbeatConnection);

            _capturedEvents = new EventCapturer();
            _settings = new ServerSettings(heartbeatInterval: Timeout.InfiniteTimeSpan);

            _subject = new ClusterableServer(_clusterId, _clusterConnectionMode, _settings, _endPoint, _connectionPoolFactory, _heartbeatConnectionFactory, _capturedEvents);
        }
Ejemplo n.º 25
0
        public Search(IEnumerable<string> searchFilter)
        {
            // TODO app setting
            Uri msgQueue = new Uri("activemq:tcp://localhost:61616");

            _factory = new ConnectionFactory(msgQueue);

            try
            {
                _connection = _factory.CreateConnection();
            }
            catch (NMSConnectionException ex)
            {
                Log.FatalException("Error connecting to MQ server", ex);
                throw;
            }
            // TODO handle -- throws connectionclosedexception
            _session = _connection.CreateSession();

            // TODO app setting
            _destination = _session.GetDestination("queue://TwitterSearchStream");
            _producer = _session.CreateProducer(_destination);

            _connection.Start();
            _producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
            _producer.RequestTimeout = TimeSpan.FromSeconds(60);

            // TODO app setting -- Put your username/password here
            searchStream = new SearchStream(uri, "username", "password");
            searchStream.StatusReceived += new EventHandler<StreamEvent>(searchStream_StatusReceived);

            var searchTerms = new Dictionary<string, string>();
            searchTerms.Add("track", string.Join(",", searchFilter.Select(HttpUtility.UrlEncode)));

            searchStream.StartStream(searchTerms);

            while (true)
            {
                Thread.Sleep(1000);
            }
        }
Ejemplo n.º 26
0
        public void RegisteredErrorHandlerIsInvokedOnException()
        {
            SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();

            ISession session = A.Fake <ISession>();

            A.CallTo((() => session.GetQueue(DESTINATION_NAME))).Returns(QUEUE_DESTINATION);
            A.CallTo((() => session.CreateConsumer(QUEUE_DESTINATION, null))).Returns(messageConsumer);
            // an exception is thrown, so the rollback logic is being applied here...
            A.CallTo((() => session.Transacted)).Returns(false);

            IConnection connection = A.Fake <IConnection>();

            connection.ExceptionListener += container.OnException;
            A.CallTo((() => connection.CreateSession(container.SessionAcknowledgeMode))).Returns(session);
            connection.Start();

            IConnectionFactory connectionFactory = A.Fake <IConnectionFactory>();

            A.CallTo((() => connectionFactory.CreateConnection())).Returns(connection);

            IllegalStateException theException = new IllegalStateException(EXCEPTION_MESSAGE);

            IErrorHandler errorHandler = A.Fake <IErrorHandler>();

            errorHandler.HandleError(theException);

            IMessage message = A.Fake <IMessage>();

            container.ConnectionFactory = connectionFactory;
            container.DestinationName   = DESTINATION_NAME;
            container.MessageListener   = new BadSessionAwareMessageListener(theException);
            container.ErrorHandler      = errorHandler;
            container.AfterPropertiesSet();

            // manually trigger an Exception with the above bad MessageListener...
            messageConsumer.SendMessage(message);
        }
Ejemplo n.º 27
0
        private IAutorecoveringConnection Connect()
        {
            var endpoints = configuration.Hosts.Select(x =>
            {
                var endpoint = new AmqpTcpEndpoint(x.Host, x.Port);
                if (x.Ssl.Enabled)
                {
                    endpoint.Ssl = x.Ssl;
                }
                else if (configuration.Ssl.Enabled)
                {
                    endpoint.Ssl = configuration.Ssl;
                }
                return(endpoint);
            }).ToArray();

            var connection = connectionFactory.CreateConnection(endpoints) as IAutorecoveringConnection;

            if (connection == null)
            {
                throw new NotSupportedException("Non-recoverable connection is not supported");
            }

            connection.ConnectionShutdown  += OnConnectionShutdown;
            connection.ConnectionBlocked   += OnConnectionBlocked;
            connection.ConnectionUnblocked += OnConnectionUnblocked;
            connection.RecoverySucceeded   += OnConnectionRecovered;

            logger.InfoFormat(
                "Connected to broker {broker}, port {port}",
                connection.Endpoint.HostName,
                connection.Endpoint.Port
                );

            eventBus.Publish(new ConnectionCreatedEvent(connection.Endpoint));

            return(connection);
        }
Ejemplo n.º 28
0
        private void Connect()
        {
            if (connection == null || !connection.IsOpen)
            {
                lock (syncLock)
                {
                    if (connection == null || !connection.IsOpen)
                    {
                        if (connection != null)
                        {
                            try
                            {
                                // when the broker connection is lost
                                // and ShutdownReport.Count > 0 RabbitMQ.Client
                                // throw an exception, but before the IConnection.Abort()
                                // is invoked
                                // https://github.com/rabbitmq/rabbitmq-dotnet-client/blob/ea913903602ba03841f2515c23f843304211cd9e/projects/client/RabbitMQ.Client/src/client/impl/Connection.cs#L1070
                                connection.Dispose();
                            }
                            catch
                            {
                                if (connection.CloseReason != null)
                                {
                                    this.logger.InfoWrite("Connection '{0}' has shutdown. Reason: '{1}'",
                                                          connection, connection.CloseReason.Cause);
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }

                        connection = connectionFactory.CreateConnection();
                    }
                }
            }
        }
Ejemplo n.º 29
0
        public static void rabbitmq(IConnectionFactory connFactory)
        {
            Console.WriteLine("Start!");
            using (IConnection conn = connFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    //String queueName = String.Empty;

                    string queueName = "queue1";

                    //声明一个队列
                    channel.QueueDeclare(
                        queue: queueName, ////消息队列名称
                        durable: false,   //是否缓存
                        exclusive: false,
                        autoDelete: false,
                        arguments: null
                        );
                    //告诉Rabbit每次只能向消费者发送一条信息,再消费者未确认之前,不再向他发送信息
                    channel.BasicQos(0, 1, false);
                    //创建消费者对象
                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (model, ea) =>
                    {
                        Thread.Sleep(2000);
                        byte[] message = ea.Body;//接收的消息
                        Console.WriteLine("接收到的消息为:" + Encoding.UTF8.GetString(message));
                        //返回消息确认
                        channel.BasicAck(ea.DeliveryTag, true);
                    };
                    //消费者开启监听
                    //将autoAck设置false 关闭自动确认
                    channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
                    Console.ReadKey();
                }
            }
        }
Ejemplo n.º 30
0
 public static void CreateQueue(this IConnectionFactory connectionFactory, string queue)
 {
     using (var conn = connectionFactory.CreateConnection())
         using (var model = conn.CreateModel())
         {
             try
             {
                 model.QueueDeclarePassive(queue);
             }
             catch (Exception e)
             {
                 // Queue does not exist, create it
                 GetOpenedModelIfClosed(conn, model)
                 .QueueDeclare(queue, true, false, false, HighAvaiableQueueArguments);
             }
             finally
             {
                 // Declare with routing bindings
                 try
                 {
                     model.ExchangeDeclarePassive(queue);
                     model.ExchangeDeclarePassive(DeclareWithRebusDirectExchangeType);
                 }
                 catch (Exception e)
                 {
                     var newModel = GetOpenedModelIfClosed(conn, model);
                     newModel.ExchangeDeclare(queue, DirectExchangeType, true);
                     newModel.ExchangeDeclare(DeclareWithRebusDirectExchangeType, DirectExchangeType, true);
                 }
                 finally
                 {
                     var newModel = GetOpenedModelIfClosed(conn, model);
                     newModel.QueueBind(queue, queue, queue, null);
                     newModel.QueueBind(queue, DeclareWithRebusDirectExchangeType, queue, null);
                 }
             }
         }
 }
        public bool TryConnect()
        {
            Logger.LogInformation("Tentando conectar ao RabbitMQ");

            lock (sync_root)
            {
                var policy = RetryPolicy.Handle <SocketException>()
                             .Or <BrokerUnreachableException>()
                             .WaitAndRetry(RetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                    Logger.LogWarning(ex, "Não foi possível conectar ao RabbitMQ após {TimeOut}s ({ExceptionMessage})", $"{time.TotalSeconds:n1}", ex.Message);
                }
                                           );

                policy.Execute(() =>
                {
                    Connection = ConnectionFactory
                                 .CreateConnection();
                });

                if (IsConnected)
                {
                    Connection.ConnectionShutdown += OnConnectionShutdown;
                    Connection.CallbackException  += OnCallbackException;
                    Connection.ConnectionBlocked  += OnConnectionBlocked;

                    Logger.LogInformation("Client RabbitMQ estabeleceu conexão com '{HostName}'", Connection.Endpoint.HostName);

                    return(true);
                }
                else
                {
                    Logger.LogCritical("ERRO FATAL: Não foi possível conectar ao RabbitMQ");

                    return(false);
                }
            }
        }
Ejemplo n.º 32
0
        public bool TryConnect()
        {
            _logger.LogInformation("O RabbitMQ Client está tentando se conectar");

            lock (sync_root)
            {
                var policy = RetryPolicy.Handle <SocketException>()
                             .Or <BrokerUnreachableException>()
                             .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                    _logger.LogWarning(ex, "O RabbitMQ Client não pôde se conectar após {TimeOut}s ({ExceptionMessage})", $"{time.TotalSeconds:n1}", ex.Message);
                }
                                           );

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

                if (IsConnected)
                {
                    _connection.ConnectionShutdown += OnConnectionShutdown;
                    _connection.CallbackException  += OnCallbackException;
                    _connection.ConnectionBlocked  += OnConnectionBlocked;

                    _logger.LogInformation("O RabbitMQ Client adquiriu uma conexão persistente com '{HostName}' e está inscrito em eventos de falha", _connection.Endpoint.HostName);

                    return(true);
                }
                else
                {
                    _logger.LogCritical("FATAL ERROR: RabbitMQ conexões não puderam ser criadas e abertas");

                    return(false);
                }
            }
        }
        public bool TryConnect()
        {
            //_logger.LogInformation("RabbitMQ Client is trying to connect");

            lock (sync_root)
            {
                var policy = RetryPolicy.Handle <SocketException>()
                             .Or <BrokerUnreachableException>()
                             .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                    //_logger.LogWarning(ex.ToString());
                }
                                           );

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

                if (IsConnected)
                {
                    _connection.ConnectionShutdown += OnConnectionShutdown;
                    _connection.CallbackException  += OnCallbackException;
                    _connection.ConnectionBlocked  += OnConnectionBlocked;

                    //_logger.LogInformation($"RabbitMQ persistent connection acquired a connection {_connection.Endpoint.HostName} and is subscribed to failure events");

                    return(true);
                }
                else
                {
                    //_logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened");

                    return(false);
                }
            }
        }
Ejemplo n.º 34
0
        public bool TryConnect()
        {
            _logger.Info("TryConnect", "DefaultRabbitMQPersistentConnection", "RabbitMQ Client is trying to connect");

            lock (sync_root)
            {
                var policy = RetryPolicy.Handle <SocketException>()
                             .Or <BrokerUnreachableException>()
                             .WaitAndRetry(_timeSpans, (ex, time) =>
                {
                    _logger.Warn("TryConnect/WaitAndRetry", "DefaultRabbitMQPersistentConnection", ex.ToString());
                }
                                           );

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

                if (IsConnected)
                {
                    _connection.ConnectionShutdown += OnConnectionShutdown;
                    _connection.CallbackException  += OnCallbackException;
                    _connection.ConnectionBlocked  += OnConnectionBlocked;

                    _logger.Info("TryConnect", "DefaultRabbitMQPersistentConnection", $"RabbitMQ persistent connection acquired a connection {_connection.Endpoint.HostName} and is subscribed to failure events");

                    return(true);
                }
                else
                {
                    _logger.Fatal("TryConnect", "DefaultRabbitMQPersistentConnection", "FATAL ERROR: RabbitMQ connections could not be created and opened");

                    return(false);
                }
            }
        }
Ejemplo n.º 35
0
        public bool TryConnect()
        {
            _logger.LogInformation("RabbitMQ Client tentando conexão...");

            lock (sync_root)
            {
                var policy = RetryPolicy.Handle <SocketException>()
                             .Or <BrokerUnreachableException>()
                             .WaitAndRetry(_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 (IsConnected)
                {
                    _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);

                    return(true);
                }
                else
                {
                    _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened");

                    return(false);
                }
            }
        }
        public bool TryConnect()
        {
            lock (syncRoot)
            {
                RetryPolicy policy = Policy
                                     .Handle <SocketException>()
                                     .Or <BrokerUnreachableException>()
                                     .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

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

                if (!IsConnected)
                {
                    return(false);
                }

                _connection.ConnectionShutdown += (o, e) => { if (!_disposed)
                                                              {
                                                                  TryConnect();
                                                              }
                };
                _connection.CallbackException += (o, e) => { if (!_disposed)
                                                             {
                                                                 TryConnect();
                                                             }
                };
                _connection.ConnectionBlocked += (o, e) => { if (!_disposed)
                                                             {
                                                                 TryConnect();
                                                             }
                };

                return(true);
            }
        }
Ejemplo n.º 37
0
        private void TryConnect()
        {
            Task.Factory.StartNew(() =>
            {

                while (!_cts.IsCancellationRequested)
                {
                    if (!_isConnect)
                    {
                        _logger.Info("开始连接指令队列服务器![{0}-{1}]".GetFormat(_name, _uri));
                        try
                        {
                            _factory = new ConnectionFactory(_uri);
                            _connection = _factory.CreateConnection();
                            _connection.ConnectionInterruptedListener += () =>
                            {
                                _logger.Error("与指令队列服务器断开连接![{0}-{1}]".GetFormat(_name, _uri));
                                _isConnect = false;
                            };
                            _connection.ClientId = _clientId;
                            _connection.Start();
                            _session = _connection.CreateSession();
                            _consumer = _session.CreateDurableConsumer(new ActiveMQTopic(_name), _connection.ClientId, null, false);
                            _consumer.Listener += OnReceived;
                            _isConnect = true;
                            _logger.Info("连接指令队列服务器成功![{0}-{1}]".GetFormat(_name, _uri));
                        }
                        catch (Exception ex)
                        {
                            _logger.Error("连接指令队列服务器失败![{0}-{1}]".GetFormat(_name, _uri), ex);
                            _isConnect = false;
                        }
                    }
                    Thread.Sleep(10 * 1000);
                }

            }, _cts.Token);
        }
Ejemplo n.º 38
0
    public void Setup()
    {
        XMSFactoryFactory  xff = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
        IConnectionFactory cf  = xff.CreateConnectionFactory();

        cf.SetStringProperty(XMSC.WMQ_HOST_NAME, "10.87.188.156(7111)");
        cf.SetIntProperty(XMSC.WMQ_PORT, 7111);
        cf.SetStringProperty(XMSC.WMQ_CHANNEL, "QMEIGS1.CRM.SVRCONN");
        cf.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT);
        cf.SetStringProperty(XMSC.WMQ_QUEUE_MANAGER, "QMEIGS1");
        cf.SetIntProperty(XMSC.WMQ_BROKER_VERSION, XMSC.WMQ_BROKER_V1);
        IConnection conn = cf.CreateConnection();

        Console.WriteLine("connection created");
        ISession         sess     = conn.CreateSession(false, AcknowledgeMode.AutoAcknowledge);
        IDestination     dest     = sess.CreateQueue("DOX.APYMT.ESB.SSK.RPO.02");
        IMessageConsumer consumer = sess.CreateConsumer(dest);
        MessageListener  ml       = new MessageListener(OnMessage);

        consumer.MessageListener = ml;
        conn.Start();
        Console.WriteLine("Consumer started");
    }
Ejemplo n.º 39
0
        private void jmsInitial()
        {
            try
            {
                //Console.WriteLine("url:" + serverinfo.Url + ";" + serverinfo.QueueName);
                _factory = new ConnectionFactory(this._serverinfo.Url);
                //_factory.UseCompression = true;
                _connection = _factory.CreateConnection();
                _session    = _connection.CreateSession(AcknowledgementMode.DupsOkAcknowledge);
                _producer   = _session.CreateProducer(
                    new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(this._serverinfo.QueueName));

                _tagsBuilder = new XtiveTags.Builder();
                Thread thread = new Thread(new ThreadStart(checkTags));
                thread.IsBackground = true;
                thread.Start();
            }
            catch (Exception msg)
            {
                //出错信息
                log.Error(msg.Message);
            }
        }
Ejemplo n.º 40
0
        public RabbitMessageBus(IConnectionFactory connectionFactory,
                                IMessageSerializer messageSerializer,
                                IMessageHandlerExecutionContext messageHandlerExecutionContext,
                                string exchangeName,
                                string exchangeType = ExchangeType.Fanout,
                                string queueName    = null,
                                bool autoAck        = false)
            : base(messageSerializer, messageHandlerExecutionContext)
        {
            // Initializes the local variables
            this.connectionFactory = connectionFactory;
            this.connection        = connectionFactory.CreateConnection();
            this.channel           = connection.CreateModel();
            this.exchangeType      = exchangeType;
            this.exchangeName      = exchangeName;
            this.autoAck           = autoAck;

            // Declares the exchange
            this.channel.ExchangeDeclare(this.exchangeName, this.exchangeType);

            // Initializes the consumer of the message queue
            this.queueName = this.InitializeMessageConsumer(queueName);
        }
Ejemplo n.º 41
0
        private void CreateMocks()
        {
            mockConnectionFactory = A.Fake <IConnectionFactory>();
            mockConnection        = A.Fake <IConnection>();
            mockSession           = A.Fake <ISession>();

            IQueue queue = A.Fake <IQueue>();

            A.CallTo(() => mockConnectionFactory.CreateConnection()).Returns(mockConnection).Once();
            if (UseTransactedTemplate)
            {
                A.CallTo(() => mockConnection.CreateSession(AcknowledgementMode.Transactional)).Returns(mockSession).Once();
            }
            else
            {
                A.CallTo(() => mockConnection.CreateSession(AcknowledgementMode.AutoAcknowledge)).Returns(mockSession).Once();
            }

            A.CallTo(() => mockSession.Transacted).Returns(true);

            mockDestinationResolver = A.Fake <IDestinationResolver>();
            A.CallTo(() => mockDestinationResolver.ResolveDestinationName(mockSession, "testDestination", false)).Returns(queue);
        }
Ejemplo n.º 42
0
        public bool TryConnect()
        {
            lock (sync_root)
            {
                connection = connectionFactory.CreateConnection();
                if (IsConnected)
                {
                    connection.ConnectionShutdown += OnConnectionShutdown;
                    connection.ConnectionBlocked  += OnConnectionBlocked;
                    connection.CallbackException  += OnCallbackException;

                    logger.LogInformation("RabbitMQ connect to {HostName}", connection.Endpoint.HostName);

                    return(true);
                }
                else
                {
                    logger.LogCritical("RabbitMQ connection can not open");

                    return(false);
                }
            }
        }
        public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                // If no factory was provided then we're stuck using the passed in connection
                // regardless of the state it may be in. We don't have a way to attempt to
                // create a new connection :(
                if (_connectionFactory == null)
                {
                    return(TestConnection(_rmqConnection));
                }

                using (var connection = _connectionFactory.CreateConnection())
                {
                    return(TestConnection(connection));
                }
            }
            catch (Exception ex)
            {
                return(Task.FromResult(
                           new HealthCheckResult(context.Registration.FailureStatus, exception: ex)));
            }
        }
Ejemplo n.º 44
0
        public void ListenMasterLocalFilesRequests()
        {
            _xffReadFactory    = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
            _connectionFactory = _xffReadFactory.CreateConnectionFactory();
            _connectionFactory.SetStringProperty(XMSC.WMQ_HOST_NAME, LMApplicationConfigurationdetails.RequestConnection);
            _connectionFactory.SetIntProperty(XMSC.WMQ_PORT, LMApplicationConfigurationdetails.RequestPort);
            _connectionFactory.SetStringProperty(XMSC.WMQ_CHANNEL, LMApplicationConfigurationdetails.RequestChannel);
            _connectionFactory.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT);
            _connectionFactory.SetStringProperty(XMSC.WMQ_QUEUE_MANAGER, LMApplicationConfigurationdetails.RequestManger);
            _connectionFactory.SetIntProperty(XMSC.WMQ_BROKER_VERSION, XMSC.WMQ_BROKER_V1);
            _connectionFactory.SetStringProperty(XMSC.WMQ_PROVIDER_VERSION, MQConfigurationSettings.WMQ_PROVIDER_VERSION);
            _mqConnection  = _connectionFactory.CreateConnection();
            _newSesstion   = _mqConnection.CreateSession(false, AcknowledgeMode.AutoAcknowledge);
            _mqDestination =
                _newSesstion.CreateQueue(string.Format("queue://{0}/{1}",
                                                       LMApplicationConfigurationdetails.RequestManger, LMApplicationConfigurationdetails.RequestQueueName));
            _mqMessageConsumer = _newSesstion.CreateConsumer(_mqDestination);
            MessageListener ml = OnFilesReceived;

            _mqMessageConsumer.MessageListener = ml;
            _mqConnection.Start();
            //Thread.Sleep(int.MaxValue);
        }
        public bool TryConnect()
        {
            var policy = Policy.Handle <BrokerUnreachableException>()
                         .Or <SocketException>()
                         .WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
            {
                _logger.LogError(ex, "Unable to connect RabbitMq");
            });

            policy.Execute(() =>
            {
                Connection = _connectionFactory.CreateConnection(ConnectionProviderName);
                if (IsConnected)
                {
                    Connection.ConnectionShutdown += OnConnectionShutdown;
                    Connection.CallbackException  += OnCallbackException;
                    Connection.ConnectionBlocked  += OnConnectionBlocked;
                    _logger.LogWarning($"RabbitMQ persistent connection acquired a connection {Connection.Endpoint.HostName} and is subscribed to failure events");
                }
            });

            return(true);
        }
Ejemplo n.º 46
0
        public void TestDestinations(
            [Values("queue://ZMQTestQueue", "topic://ZMQTestTopic", "temp-queue://ZMQTempQueue", "temp-topic://ZMQTempTopic")]
            string destination,
            [Values(typeof(Queue), typeof(Topic), typeof(TemporaryQueue), typeof(TemporaryTopic))]
            Type destinationType)
        {
            IConnectionFactory factory = NMSConnectionFactory.CreateConnectionFactory(new Uri("zmq:tcp://localhost:5556"));

            Assert.IsNotNull(factory, "Error creating connection factory.");
            using (IConnection connection = factory.CreateConnection())
            {
                Assert.IsNotNull(connection, "Problem creating connection class. Usually problem with libzmq and clrzmq ");
                using (ISession session = connection.CreateSession())
                {
                    Assert.IsNotNull(session, "Error creating session.");
                    using (IDestination testDestination = session.GetDestination(destination))
                    {
                        Assert.IsNotNull(testDestination, "Error creating test destination: {0}", destination);
                        Assert.IsInstanceOf(destinationType, testDestination, "Wrong destintation type.");
                    }
                }
            }
        }
Ejemplo n.º 47
0
        public void Setup()
        {
            XMSFactoryFactory  xff = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
            IConnectionFactory cf  = xff.CreateConnectionFactory();

            cf.SetStringProperty(XMSC.WMQ_HOST_NAME, "localhost");
            cf.SetIntProperty(XMSC.WMQ_PORT, 1414);
            cf.SetStringProperty(XMSC.WMQ_CHANNEL, "CLIENT");
            cf.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT);
            cf.SetStringProperty(XMSC.WMQ_QUEUE_MANAGER, "QM_LOCAL");
            cf.SetIntProperty(XMSC.WMQ_BROKER_VERSION, XMSC.WMQ_BROKER_V1);
            IConnection conn = cf.CreateConnection();

            Console.WriteLine("connection created");
            ISession         sess     = conn.CreateSession(false, AcknowledgeMode.AutoAcknowledge);
            IDestination     dest     = sess.CreateQueue("queue://q");
            IMessageConsumer consumer = sess.CreateConsumer(dest);
            MessageListener  ml       = new MessageListener(OnMessage);

            consumer.MessageListener = ml;
            conn.Start();
            Console.WriteLine("Consumer started");
        }
Ejemplo n.º 48
0
        void AMQStart()
        {
            //GlobalAMQSettings global_AMQ_settings = FindObjectOfType<GlobalAMQSettings>();
            //string address = global_AMQ_settings.GetComponent<GlobalAMQSettings>().address;
            //int port = global_AMQ_settings.GetComponent<GlobalAMQSettings>().port;
            try {
                factory = new NMSConnectionFactory(URI);
                //connection = factory.CreateConnection("admin", "admin");
                connection = factory.CreateConnection();
                Debug.Log("AMQ connecting to "+URI);
                session = connection.CreateSession();
                networkOpen = true;
                connection.Start();
            } catch (System.Exception e) {
                Debug.LogWarning("AMQ Start Exception " + e);
            }

            amqWriterThread = new Thread(new ThreadStart(AMQWriter));
            amqWriterThread.Start();

            amqReaderThread = new Thread(new ThreadStart(AMQReader));
            amqReaderThread.Start();
        }
Ejemplo n.º 49
0
        public void Send(string message, string queueName)
        {
            try
            {
                var messageBytes = Encoding.UTF8.GetBytes(message);

                using (var connection = _connectionFactory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queue: queueName, exclusive: false);
                        channel.BasicPublish(exchange: "",
                                             routingKey: queueName,
                                             body: messageBytes);

                        _logger.LogDebug($"Sent {message} on {queueName}");
                    }
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Error in Send");
                throw;
            }
        }
Ejemplo n.º 50
0
        public RabbitMQEventBus(IEventHandlerExecutionContext _eventHandlerExecutionContext,
                                ILogger <RabbitMQEventBus> _logger,
                                IConnectionFactory _connectionFactory,
                                string _exchangeName,
                                string _exchangeType = ExchangeType.Fanout,
                                string _queueName    = null,
                                bool _autoAck        = false
                                )
            : base(_eventHandlerExecutionContext)
        {
            connectionFactory = _connectionFactory;
            logger            = _logger;
            connection        = connectionFactory.CreateConnection();
            channel           = connection.CreateModel();
            exchangeType      = _exchangeType;
            exchangeName      = _exchangeName;
            autoAck           = _autoAck;

            channel.ExchangeDeclare(exchangeName, exchangeType);
            queueName = InitializeEventConsumer(_queueName);

            logger.LogInformation($"RabbitMQEventBus 构造函数调用完成* Hash Code:{this.GetHashCode()}.");
        }
Ejemplo n.º 51
0
        public void PublishMessage <T>(T message, string queueName) where T : class
        {
            var connection = _connectionFactory.CreateConnection();
            var channel    = connection.CreateModel();


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

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

            var properties = channel.CreateBasicProperties();

            properties.Persistent = true;

            channel.BasicPublish(exchange: "",
                                 routingKey: queueName,
                                 basicProperties: properties,
                                 body: body);
        }
        public static IConnection CreateConnection(
            this IConnectionFactory factory,
            TimeSpan timeout
            )
        {
            var connection = null as IConnection;
            var connectedOrTimedOutEvent = new AutoResetEvent(false);

            Task.Delay(timeout)
            .ContinueWith(task => connectedOrTimedOutEvent.Set());
            Task.Run(() =>
            {
                connection = factory.CreateConnection();
                if (!connection.IsOpen)
                {
                    connection = null;
                }
                connectedOrTimedOutEvent.Set();
            });

            connectedOrTimedOutEvent.WaitOne();
            return(connection);
        }
Ejemplo n.º 53
0
        //交换机模式exchange(交换机)模式(发布订阅模式(fanout不建议使用), 路由模式(direct), 通配符模式(topic))
        /// <summary>
        /// 交换机exchange发布订阅模式fanout
        /// </summary>
        /// <param name="connFactory"></param>
        public void rabbitmqExchangeFanout(IConnectionFactory connFactory)
        {
            using (IConnection conn = connFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    //交换机名称
                    string exchangeName = "exchange1";

                    channel.ExchangeDeclare(exchange: exchangeName, type: "fanout");

                    //channel.ConfirmSelect();
                    //Console.WriteLine("消息内容:");
                    String message = this.textBox1.Text;
                    //消息内容
                    byte[] body = Encoding.UTF8.GetBytes(message);
                    //发送消息
                    channel.BasicPublish(exchange: exchangeName, routingKey: "", basicProperties: null, body: body);
                    //var isok = channel.WaitForConfirms();
                    Console.WriteLine("成功发送消息11:" + message + ";33"); // + isok.ToString());
                }
            }
        }
Ejemplo n.º 54
0
        public bool TryConnect(PolicyFactory persisterConnectionPolicyFactory)
        {
            lock (_lockObject)
            {
                if (IsConnected)
                {
                    return(true);
                }

                persisterConnectionPolicyFactory(_logger)
                .Execute(() =>
                {
                    _connection = _factory.CreateConnection();
                });

                if (!IsConnected)
                {
                    return(false);
                }

                return(true);
            }
        }
Ejemplo n.º 55
0
        private void ConnectToMessageQueue(Common.Model.RabbitMQ.Root settings)
        {
            connectionFactory.UserName = settings.Username;
            connectionFactory.Password = settings.Password;

            var timeout = DateTime.Now.AddSeconds(30);

            do
            {
                try
                {
                    this.connection = connectionFactory.CreateConnection(settings.Hosts.Select(h => h.Address).ToList());
                }
                catch (BrokerUnreachableException)
                {
                }
            }while (DateTime.Now < timeout && this.connection == null);

            if (this.connection == null)
            {
                throw new TimeoutException("Could not connect to RabbitMQ instance.");
            }
        }
Ejemplo n.º 56
0
        public Queue()
        {
            Uri msgQueue = new Uri("activemq:tcp://localhost:61616");

            _factory = new ConnectionFactory(msgQueue);
            try
            {
                _connection = _factory.CreateConnection();
            }
            catch (NMSConnectionException exc)
            {
                // TODO handle no server found issue
            }
            // TODO check _connection for null -- probably means server not found
            _connection.RequestTimeout = TimeSpan.FromSeconds(60);
            _session = _connection.CreateSession();

            // TODO need to find out if queue exists.
            // It creates a new queue if it doesn't exist.
            _destination = _session.GetDestination("queue://TwitterSearchStream");
            _consumer = _session.CreateConsumer(_destination);
            _connection.Start();
            //_consumer.Listener += message =>
            //                        {
            //                            var msg = message as ITextMessage;
            //                            ProcessResults(msg.Text);
            //                        };
            _connection.ExceptionListener += _connection_ExceptionListener;
            _connection.ConnectionInterruptedListener += _connection_ConnectionInterruptedListener;

            //while (true)
            //{
            //    Thread.Sleep(1000);
            //}

            StartReceive();
        }
        public void CachedMessageProducerTwoRequests()
        {
            IConnectionFactory connectionFactory = (IConnectionFactory)mocks.CreateMock(typeof(IConnectionFactory));
            IConnection        connection        = new TestConnection();

            Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Once();

            mocks.ReplayAll();


            CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();

            cachingConnectionFactory.TargetConnectionFactory = connectionFactory;
            IConnection con1 = cachingConnectionFactory.CreateConnection();

            ISession            sessionA  = con1.CreateSession(true, SessionMode.SessionTransacted);
            Topic               dest      = new Topic("test.topic");
            IMessageProducer    producerA = sessionA.CreateProducer(dest);
            TestMessageProducer tmpA      = GetTestMessageProducer(producerA);


            ISession            sessionB  = con1.CreateSession(true, SessionMode.SessionTransacted);
            IMessageProducer    producerB = sessionB.CreateProducer(dest);
            TestMessageProducer tmpB      = GetTestMessageProducer(producerB);

            Assert.AreNotSame(tmpA, tmpB);

            sessionA.Close();

            ISession            sessionC  = con1.CreateSession(true, SessionMode.SessionTransacted);
            IMessageProducer    producerC = sessionC.CreateProducer(dest);
            TestMessageProducer tmpC      = GetTestMessageProducer(producerC);

            Assert.AreSame(tmpA, tmpC);

            mocks.VerifyAll();
        }
Ejemplo n.º 58
0
        protected void TryCreateConnectionFactory(object stateInfo)
        {
            connection = null;
            //Log.Debug("RabbitMq: TryCreateConnectionFactory Creating connection factory on {0} - {1}", hostNames, stateInfo);

            if (stateInfo != null)
            {
                var autoEvent = (AutoResetEvent) stateInfo;
                autoEvent.Set();
            }
            var tempHostNames = hostNames;
            //hostNames.Shuffle();
            foreach (var hostName in tempHostNames)
            {
                try
                {
                    factory = new ConnectionFactory { HostName = hostName, UserName = userName, Password = password, NetworkRecoveryInterval = TimeSpan.FromMilliseconds(timeout) };
                    connection = factory.CreateConnection();
                    waitingToConnect = false;
                    break;
                }
                catch (SocketException se)
                {
                    Log.Error(se, "RabbitMq: TryCreateConnectionFactory has an Error creating connection to host {0}", hostName);
                }
                catch (BrokerUnreachableException be)
                {
                    Log.Error(be, "RabbitMq: TryCreateConnectionFactory Cannot reach broker for host {0}", hostName);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "RabbitMq: TryCreateConnectionFactory has an Error with {0} - {1}", hostName, ex.Message);
                }
            }
            if (connection == null) StartTryToConnect();
        }
Ejemplo n.º 59
0
        public void Start()
        {
            factory = new ConnectionFactory(URI);

            if (USERNAME != "")
            {
                connection = factory.CreateConnection(USERNAME, PASSWORD);
            }
            else
            {
                connection = factory.CreateConnection();
            }
            connection.Start();
            session = connection.CreateSession();
        }
        /// <summary>
        /// Private method, that must be run for the client to work.
        /// <remarks>See constructor</remarks>
        /// </summary>
        private void InitializeEndpoint()
        {
            // prepare endpoint
            _connectionFactory = GetConnectionFactory();
            _connection = _connectionFactory.CreateConnection();
            _model = _connection.CreateModel();

            _properties = _model.CreateBasicProperties();
            _properties.DeliveryMode = (byte)_config.DeliveryMode; //persistance
        }