示例#1
0
        public static void Main(string[] args)
        {
            try
            {
                const string connectionUrl = @"amqp://*****:*****@clientid/test?brokerlist='tcp://localhost:5672'";
                const string queueName     = @"test-queue";

                var connectionInfo = QpidConnectionInfo.FromUrl(connectionUrl);
                var connection     = new AMQConnection(connectionInfo);
                var channel        = connection.CreateChannel(false, AcknowledgeMode.AutoAcknowledge, 1);

                channel.DeclareQueue(queueName, false, true, true);
                channel.Bind(queueName, ExchangeNameDefaults.DIRECT, queueName);
                IMessageConsumer consumer = channel.CreateConsumerBuilder(queueName).Create();
                connection.Start();

                ITextMessage message = (ITextMessage)consumer.Receive();
                Console.WriteLine("Got: " + message.Text);
                connection.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
示例#2
0
        /// <summary> Sets up the nth test end-point. </summary>
        ///
        /// <param name="n">The index of the test end-point to set up.</param>
        /// <param name="producer"><tt>true</tt> to set up a producer on the end-point.</param>
        /// <param name="consumer"><tt>true</tt> to set up a consumer on the end-point.</param>
        /// <param name="routingKey">The routing key for the producer to send on.</param>
        /// <param name="ackMode">The ack mode for the end-points channel.</param>
        /// <param name="transacted"><tt>true</tt> to use transactions on the end-points channel.</param>
        /// <param name="exchangeName">The exchange to produce or consume on.</param>
        /// <param name="declareBind"><tt>true</tt> if the consumers queue should be declared and bound, <tt>false</tt> if it has already been.</param>
        /// <param name="durable"><tt>true</tt> to declare the consumers queue as durable.</param>
        /// <param name="subscriptionName">If durable is true, the fixed unique queue name to use.</param>
        /// <param name="exclusive"><tt>true</tt> declare queue as exclusive.</param>
        /// <param name="browse"><tt>true</tt> only browse, don''t consume.</param>
        public void SetUpEndPoint(int n, bool producer, bool consumer, string routingKey, AcknowledgeMode ackMode, bool transacted,
                                  string exchangeName, bool declareBind, bool durable, string subscriptionName, bool exclusive, bool browse)
        {
            // Allow client id to be fixed, or undefined.
            {
                // Use unique id for end point.
                connectionInfo = QpidConnectionInfo.FromUrl(connectionUri);

                connectionInfo.ClientName = "test" + n;
            }

            testConnection[n] = new AMQConnection(connectionInfo);
            testConnection[n].Start();
            testChannel[n] = testConnection[n].CreateChannel(transacted, ackMode);

            if (producer)
            {
                testProducer[n] = testChannel[n].CreatePublisherBuilder()
                                  .WithExchangeName(exchangeName)
                                  .WithRoutingKey(routingKey)
                                  .Create();
            }

            if (consumer)
            {
                string queueName;

                // Use the subscription name as the queue name if the subscription is durable, otherwise use a generated name.
                if (durable)
                {
                    // The durable queue is declared without auto-delete, and passively, in case it has already been declared.
                    queueName = subscriptionName;

                    if (declareBind)
                    {
                        testChannel[n].DeclareQueue(queueName, durable, exclusive, false);
                        testChannel[n].Bind(queueName, exchangeName, routingKey);
                    }
                }
                else
                {
                    queueName = testChannel[n].GenerateUniqueName();

                    if (declareBind)
                    {
                        if (durable)
                        {
                            testQueue[n] = queueName;
                        }
                        testChannel[n].DeclareQueue(queueName, durable, true, true);
                        testChannel[n].Bind(queueName, exchangeName, routingKey);
                    }
                }

                testConsumer[n] = testChannel[n].CreateConsumerBuilder(queueName).WithBrowse(browse).Create();
            }
        }
        public void SimpleConnection()
        {
            IConnectionInfo connectionInfo = new QpidConnectionInfo();

            connectionInfo.VirtualHost = "test";
            connectionInfo.AddBrokerInfo(_broker);
            using (IConnection connection = new AMQConnection(connectionInfo))
            {
                Console.WriteLine("connection = " + connection);
            }
        }
        private static void MakeBrokerConnection(SslOptions options)
        {
            IConnectionInfo connectionInfo = new QpidConnectionInfo();

            connectionInfo.VirtualHost = "test";
            connectionInfo.AddBrokerInfo(new AmqBrokerInfo("amqp", "localhost", 8672, options));

            using (IConnection connection = new AMQConnection(connectionInfo))
            {
                Console.WriteLine("connection = " + connection);
            }
        }
        /// <summary>
        /// Establishes an AMQ connection. This is a simple convenience method for code that does not anticipate handling connection failures.
        /// All exceptions that indicate that the connection has failed, are allowed to fall through.
        /// </summary>
        ///
        /// <param name="brokerUrl">   The broker url to connect to, <tt>null</tt> to use the default from the properties. </param>
        /// <param name="virtualHost"> The virtual host to connectio to, <tt>null</tt> to use the default. </param>
        ///
        /// <returns> A JMS conneciton. </returns>
        public static IConnection CreateConnection(string brokerUrl, string virtualHost)
        {
            log.Info("public static Connection createConnection(string brokerUrl = " + brokerUrl + ", string virtualHost = "
                     + virtualHost + "): called");

            // Create a connection to the broker.
            IConnectionInfo connectionInfo = QpidConnectionInfo.FromUrl(brokerUrl);

            connectionInfo.VirtualHost = virtualHost;
            IConnection connection = new AMQConnection(connectionInfo);

            return(connection);
        }
示例#6
0
        private IoHandler MakeBrokerConnection(IBrokerInfo broker, AMQConnection connection)
        {
            if (broker.UseSSL)
            {
                _connector = new SslSocketConnector();
            }
            else
            {
                _connector = new SocketConnector();
            }

            Stream stream = _connector.Connect(broker);

            return(new IoHandler(stream, connection.ProtocolListener));
        }
        public void PasswordFailureConnection()
        {
            IConnectionInfo connectionInfo = new QpidConnectionInfo();

            connectionInfo.VirtualHost = "test";
            connectionInfo.Password    = "******";
            connectionInfo.AddBrokerInfo(_broker);

            using (IConnection connection = new AMQConnection(connectionInfo))
            {
                Console.WriteLine("connection = " + connection);
                // wrong
                Assert.Fail("Authentication succeeded but should've failed");
            }
        }
      /// <summary>
      /// Connect to the specified broker
      /// </summary>
      /// <param name="broker">The broker to connect to</param>
      /// <param name="connection">The AMQ connection</param>
      public void Connect(IBrokerInfo broker, AMQConnection connection)
      {
         _stopEvent = new ManualResetEvent(false);
         _protocolListener = connection.ProtocolListener;

         _ioHandler = MakeBrokerConnection(broker, connection);
         // todo: get default read size from config!

         IProtocolDecoderOutput decoderOutput =
            new ProtocolDecoderOutput(_protocolListener);
         _amqpChannel = 
            new AmqpChannel(new ByteChannel(_ioHandler), decoderOutput);

         // post an initial async read
         _amqpChannel.BeginRead(new AsyncCallback(OnAsyncReadDone), this);
      }
示例#9
0
        /// <summary>
        /// Connect to the specified broker
        /// </summary>
        /// <param name="broker">The broker to connect to</param>
        /// <param name="connection">The AMQ connection</param>
        public void Connect(IBrokerInfo broker, AMQConnection connection)
        {
            _stopEvent        = new ManualResetEvent(false);
            _protocolListener = connection.ProtocolListener;

            _ioHandler = MakeBrokerConnection(broker, connection);
            // todo: get default read size from config!

            IProtocolDecoderOutput decoderOutput =
                new ProtocolDecoderOutput(_protocolListener);

            _amqpChannel =
                new AmqpChannel(new ByteChannel(_ioHandler), decoderOutput);

            // post an initial async read
            _amqpChannel.BeginRead(new AsyncCallback(OnAsyncReadDone), this);
        }
        private static void SendMessages()
        {
            AMQConnection conn = new AMQConnection(QpidConnectionInfo.FromUrl(BaseMessagingTestFixture.connectionUri));

            conn.Start();
            IChannel          channel  = conn.CreateChannel(false, AcknowledgeMode.AutoAcknowledge);
            IMessagePublisher producer = channel.CreatePublisherBuilder().
                                         WithExchangeName(ExchangeNameDefaults.DIRECT).
                                         WithRoutingKey(TEST_ROUTING_KEY).
                                         Create();

            for (int i = 0; i < MESSAGE_COUNT; i++)
            {
                if ((i % 10) == 0)
                {
                    Console.WriteLine("Sending message " + i);
                }
                producer.Send(channel.CreateTextMessage("Msg" + i));
            }
        }
        /// <summary>
        /// Creates the test connection with a fail-over set up, and a producer/consumer pair on that connection.
        /// </summary>
        /// [SetUp]
        public void Init(IConnectionInfo connectionInfo)
        {
            //log4net.Config.BasicConfigurator.Configure();
            // Reset all counts.
            messagesSent     = 0;
            messagesReceived = 0;
            failedOver       = false;
            _extraMessage    = 0;

            PromptAndWait("Ensure both brokers are running, then press Enter");

            // Create a connection for the test.
            _connection = new AMQConnection(connectionInfo);
            _connection.ConnectionListener = this;

            // Create a consumer to receive the test messages.
            IChannel receivingChannel = _connection.CreateChannel(false, _acknowledgeMode);

            string queueName = receivingChannel.GenerateUniqueName();

            receivingChannel.DeclareQueue(queueName, false, true, true);
            receivingChannel.Bind(queueName, "amq.direct", queueName);

            IMessageConsumer consumer = receivingChannel.CreateConsumerBuilder(queueName)
                                        .WithPrefetchLow(30)
                                        .WithPrefetchHigh(60).Create();

            consumer.OnMessage = new MessageReceivedDelegate(OnMessage);
            _connection.Start();

            // Create a publisher to send the test messages.
            publishingChannel = _connection.CreateChannel(transacted, AcknowledgeMode.NoAcknowledge);
            publisher         = publishingChannel.CreatePublisherBuilder()
                                .WithRoutingKey(queueName)
                                .Create();

            _log.Debug("connection = " + _connection);
            _log.Debug("connectionInfo = " + connectionInfo);
            _log.Debug("connection.AsUrl = " + _connection.toURL());
            _log.Debug("AcknowledgeMode is " + _acknowledgeMode);
        }
示例#12
0
 public object execute(AMQConnection con)
 {
     // We wait until we are not in the middle of failover before acquiring the mutex and then proceeding.
     // Any method that can potentially block for any reason should use this class so that deadlock will not
     // occur. The FailoverException is propagated by the AMQProtocolHandler to any listeners (e.g. frame listeners)
     // that might be causing a block. When that happens, the exception is caught here and the mutex is released
     // before waiting for the failover to complete (either successfully or unsuccessfully).
     while (true)
     {
         con.ProtocolListener.BlockUntilNotFailingOver();
         lock (con.FailoverMutex)
         {
             try
             {
                 return(operation());
             }
             catch (FailoverException e)
             {
                 _log.Info("Failover exception caught during operation", e);
             }
         }
     }
 }
示例#13
0
 public object execute(AMQConnection con)
 {
     // We wait until we are not in the middle of failover before acquiring the mutex and then proceeding.
     // Any method that can potentially block for any reason should use this class so that deadlock will not
     // occur. The FailoverException is propagated by the AMQProtocolHandler to any listeners (e.g. frame listeners)
     // that might be causing a block. When that happens, the exception is caught here and the mutex is released
     // before waiting for the failover to complete (either successfully or unsuccessfully).
     while (true)
     {
         con.ProtocolListener.BlockUntilNotFailingOver();
         lock (con.FailoverMutex)
         {
             try
             {
                 return operation();
             }
             catch (FailoverException e)
             {
                 _log.Info("Failover exception caught during operation", e);
             }
         }
     }
 }
示例#14
0
        public static void Main(string[] args)
        {
            try
            {
                const string connectionUrl = @"amqp://*****:*****@clientid/test?brokerlist='tcp://localhost:5672'";
                const string queueName     = @"test-queue";

                var connectionInfo = QpidConnectionInfo.FromUrl(connectionUrl);
                var connection     = new AMQConnection(connectionInfo);
                var channel        = connection.CreateChannel(false, AcknowledgeMode.AutoAcknowledge);
                var publisher      = channel.CreatePublisherBuilder()
                                     .WithExchangeName(ExchangeNameDefaults.DIRECT)
                                     .WithRoutingKey(queueName)
                                     .Create();
                IMessage message = channel.CreateTextMessage("0123456789");
                publisher.Send(message);
                Console.WriteLine("Sent message");
                connection.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
 public BlockingSocketTransport(string host, int port, AMQConnection connection)
 {
     _host             = host;
     _port             = port;
     _protocolListener = connection.ProtocolListener;
 }
示例#16
0
 public AMQProtocolSession(IProtocolWriter protocolWriter, IConnectionCloser connectionCloser, AMQConnection connection)
 {
     _protocolWriter = protocolWriter;
     _connectionCloser = connectionCloser;
     _connection = connection;
 }
 public BlockingSocketTransport(string host, int port, AMQConnection connection)
 {
     _host = host;
     _port = port;
     _protocolListener = connection.ProtocolListener;
 }
示例#18
0
 public FailoverHandler(AMQConnection connection)
 {
     _connection = connection;
 }
 public AMQProtocolSession(IProtocolWriter protocolWriter, IConnectionCloser connectionCloser, AMQConnection connection)
 {
     _protocolWriter   = protocolWriter;
     _connectionCloser = connectionCloser;
     _connection       = connection;
 }
示例#20
0
 public AMQProtocolListener(AMQConnection connection, AMQStateManager stateManager)
 {
     _connection = connection;
     _stateManager = stateManager;
     _failoverHandler = new FailoverHandler(connection);
 }
示例#21
0
        static void Main(string[] args)
        {
            XmlConfigurator.Configure(new FileInfo("..\\..\\log.xml"));
            // DOMConfigurator.Configure()

            string          host           = ConfigurationManager.AppSettings["Host"];
            int             port           = int.Parse(ConfigurationManager.AppSettings["Port"]);
            string          virtualhost    = ConfigurationManager.AppSettings["VirtualHost"];
            string          username       = ConfigurationManager.AppSettings["Username"];
            string          password       = ConfigurationManager.AppSettings["Password"];
            IConnectionInfo connectionInfo = new QpidConnectionInfo();

            connectionInfo.VirtualHost = virtualhost;
            //connectionInfo.host = host;
            //connectionInfo.port = port;
            connectionInfo.Username = username;
            connectionInfo.Password = password;

            //Client client = new Client();

            Console.WriteLine("Client created");
            //client.Connect(host, port, virtualhost, username, password);
            IConnection clientConnection = new AMQConnection(connectionInfo);

            Console.WriteLine("Connection established");

            IClientSession ssn = client.CreateSession(50000);

            Console.WriteLine("Session created");
            ssn.QueueDeclare("queue1", null, null);
            ssn.ExchangeBind("queue1", "amq.direct", "queue1", null);


            Object wl = new Object();

            ssn.AttachMessageListener(new MyListener(ssn, wl), "myDest");

            ssn.MessageSubscribe("queue1", "myDest", MessageAcceptMode.EXPLICIT, MessageAcquireMode.PRE_ACQUIRED, null,
                                 0, null);
            DateTime start = DateTime.Now;

            // issue credits
            ssn.MessageSetFlowMode("myDest", MessageFlowMode.WINDOW);
            ssn.MessageFlow("myDest", MessageCreditUnit.BYTE, ClientSession.MESSAGE_FLOW_MAX_BYTES);
            ssn.MessageFlow("myDest", MessageCreditUnit.MESSAGE, 10000);
            ssn.Sync();


            for (int i = 0; i < 10000; i++)
            {
                ssn.MessageTransfer("amq.direct", MessageAcceptMode.NONE, MessageAcquireMode.PRE_ACQUIRED,
                                    new Header(new DeliveryProperties().SetRoutingKey("queue1"),
                                               new MessageProperties().SetMessageId(UUID.RandomUuid())),
                                    Encoding.UTF8.GetBytes("test: " + i));
            }

            lock (wl)
            {
                Monitor.Wait(wl);
            }
            DateTime now = DateTime.Now;

            Console.WriteLine("Start time " + start + " now: " + now);

            Console.WriteLine("Done time: " + (now - start));
            lock (wl)
            {
                Monitor.Wait(wl, 30000);
            }
            client.Close();
        }
      private IoHandler MakeBrokerConnection(IBrokerInfo broker, AMQConnection connection)
      {
         if ( broker.UseSSL )
         {
            _connector = new SslSocketConnector();
         } else
         {
            _connector = new SocketConnector();
         }

         Stream stream = _connector.Connect(broker);
         return new IoHandler(stream, connection.ProtocolListener);
      }
示例#23
0
 public AMQProtocolListener(AMQConnection connection, AMQStateManager stateManager)
 {
     _connection      = connection;
     _stateManager    = stateManager;
     _failoverHandler = new FailoverHandler(connection);
 }
示例#24
0
 public FailoverHandler(AMQConnection connection)
 {
     _connection = connection;
 }