Search in sources :

Example 16 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project uavstack by uavorg.

the class TestRestService method testRabbitmq.

@POST
@Path("testRabbitmq")
public void testRabbitmq(String jsonString) {
    String QUEUE_NAME = "haha";
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("guest");
    factory.setPassword("guest");
    factory.setHost("10.100.66.81");
    factory.setPort(5672);
    try {
        com.rabbitmq.client.Connection conn = factory.newConnection();
        Channel channel = conn.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello World!";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
        // System.out.println(" [x] Sent '" + message + "'");
        channel.close();
        conn.close();
        com.rabbitmq.client.Connection connection = factory.newConnection();
        Channel recvchannel = connection.createChannel();
        recvchannel.queueDeclare(QUEUE_NAME, false, false, false, null);
        com.rabbitmq.client.Consumer consumer = new DefaultConsumer(recvchannel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                Log.log(message);
            // System.out.println(" [x] Received '" + message + "'1");
            }
        };
        recvchannel.basicConsume(QUEUE_NAME, true, consumer);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    }
}
Also used : ConnectionFactory(com.rabbitmq.client.ConnectionFactory) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Channel(com.rabbitmq.client.Channel) IOException(java.io.IOException) Envelope(com.rabbitmq.client.Envelope) TimeoutException(java.util.concurrent.TimeoutException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 17 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project uavstack by uavorg.

the class TestRestService method testRabbitmq.

@GET
@Path("testRabbitmq")
public void testRabbitmq(String jsonString) {
    String QUEUE_NAME = "haha";
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("guest");
    factory.setPassword("guest");
    factory.setHost("127.0.0.1");
    factory.setPort(5672);
    try {
        com.rabbitmq.client.Connection conn = factory.newConnection();
        Channel channel = conn.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello World!";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");
        channel.close();
        conn.close();
        com.rabbitmq.client.Connection connection = factory.newConnection();
        Channel recvchannel = connection.createChannel();
        recvchannel.queueDeclare(QUEUE_NAME, false, false, false, null);
        com.rabbitmq.client.Consumer consumer = new DefaultConsumer(recvchannel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
            // System.out.println(" [x] Received '" + message + "'1");
            }
        };
        recvchannel.basicConsume(QUEUE_NAME, true, consumer);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    }
}
Also used : ConnectionFactory(com.rabbitmq.client.ConnectionFactory) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Channel(com.rabbitmq.client.Channel) IOException(java.io.IOException) Envelope(com.rabbitmq.client.Envelope) TimeoutException(java.util.concurrent.TimeoutException) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 18 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project uavstack by uavorg.

the class RabbitMQRecv method send.

@POST
@Path("rabbitmqRecv")
public void send() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("guest");
    factory.setPassword("guest");
    factory.setHost("127.0.0.1");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    DefaultConsumer consumer = new DefaultConsumer(channel) {

        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            System.out.println(properties.getHeaders());
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        }
    };
    channel.basicConsume(QUEUE_NAME, true, consumer);
}
Also used : ConnectionFactory(com.rabbitmq.client.ConnectionFactory) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) Envelope(com.rabbitmq.client.Envelope) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 19 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project spring_boot by hryou0922.

the class RpcServer method execute.

public static void execute(String host, String userName, String password) {
    // 配置连接工厂
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    // 需要在管理后台增加一个hry帐号
    factory.setUsername(userName);
    factory.setPassword(password);
    Connection connection = null;
    try {
        // 建立TCP连接
        connection = factory.newConnection();
        // 在TCP连接的基础上创建通道
        final Channel channel = connection.createChannel();
        // 声明一个rpc_queue队列
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        // 设置同时最多只能获取一个消息
        channel.basicQos(1);
        System.out.println(" [RpcServer] Awaiting RPC requests");
        // 定义消息的回调处理类
        Consumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 生成返回的结果,关键是设置correlationId值
                AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder().correlationId(properties.getCorrelationId()).build();
                // 生成返回
                String response = generateResponse(body);
                // 回复消息,通知已经收到请求
                channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                // 对消息进行应答
                channel.basicAck(envelope.getDeliveryTag(), false);
                // 唤醒正在消费者所有的线程
                synchronized (this) {
                    this.notify();
                }
            }
        };
        // 消费消息
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        // 在收到消息前,本线程进入等待状态
        while (true) {
            synchronized (consumer) {
                try {
                    consumer.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            // 空值判断,为了代码简洁略
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Also used : DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Channel(com.rabbitmq.client.Channel) Connection(com.rabbitmq.client.Connection) Envelope(com.rabbitmq.client.Envelope) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) DefaultConsumer(com.rabbitmq.client.DefaultConsumer) Consumer(com.rabbitmq.client.Consumer) AMQP(com.rabbitmq.client.AMQP)

Example 20 with DefaultConsumer

use of com.rabbitmq.client.DefaultConsumer in project graylog2-server by Graylog2.

the class AmqpConsumer method run.

public void run() throws IOException {
    if (!isConnected()) {
        connect();
    }
    for (int i = 0; i < parallelQueues; i++) {
        final String queueName = String.format(Locale.ENGLISH, queue, i);
        channel.queueDeclare(queueName, true, false, false, null);
        if (exchangeBind) {
            channel.queueBind(queueName, exchange, routingKey);
        }
        channel.basicConsume(queueName, false, new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                long deliveryTag = envelope.getDeliveryTag();
                try {
                    totalBytesRead.addAndGet(body.length);
                    lastSecBytesReadTmp.addAndGet(body.length);
                    final RawMessage rawMessage = new RawMessage(body);
                    // TODO figure out if we want to unsubscribe after a certain time, or if simply blocking is enough here
                    if (amqpTransport.isThrottled()) {
                        amqpTransport.blockUntilUnthrottled();
                    }
                    sourceInput.processRawMessage(rawMessage);
                    channel.basicAck(deliveryTag, false);
                } catch (Exception e) {
                    LOG.error("Error while trying to process AMQP message", e);
                    if (channel.isOpen()) {
                        channel.basicNack(deliveryTag, false, requeueInvalid);
                        if (LOG.isDebugEnabled()) {
                            if (requeueInvalid) {
                                LOG.debug("Re-queue message with delivery tag {}", deliveryTag);
                            } else {
                                LOG.debug("Message with delivery tag {} not re-queued", deliveryTag);
                            }
                        }
                    }
                }
            }
        });
    }
}
Also used : DefaultConsumer(com.rabbitmq.client.DefaultConsumer) AMQP(com.rabbitmq.client.AMQP) IOException(java.io.IOException) Envelope(com.rabbitmq.client.Envelope) RawMessage(org.graylog2.plugin.journal.RawMessage) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

DefaultConsumer (com.rabbitmq.client.DefaultConsumer)32 IOException (java.io.IOException)21 Envelope (com.rabbitmq.client.Envelope)20 Channel (com.rabbitmq.client.Channel)15 Test (org.junit.Test)15 AMQP (com.rabbitmq.client.AMQP)11 TimeoutException (java.util.concurrent.TimeoutException)10 Connection (com.rabbitmq.client.Connection)9 Consumer (com.rabbitmq.client.Consumer)9 ConnectionFactory (com.rabbitmq.client.ConnectionFactory)8 CountDownLatch (java.util.concurrent.CountDownLatch)4 BasicProperties (com.rabbitmq.client.AMQP.BasicProperties)3 AutorecoveringConnection (com.rabbitmq.client.impl.recovery.AutorecoveringConnection)3 KeyManagementException (java.security.KeyManagementException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 UUID (java.util.UUID)3 Path (javax.ws.rs.Path)3 AlreadyClosedException (com.rabbitmq.client.AlreadyClosedException)2 Recoverable (com.rabbitmq.client.Recoverable)2 RecoveryListener (com.rabbitmq.client.RecoveryListener)2