Search in sources :

Example 21 with Envelope

use of com.rabbitmq.client.Envelope in project rabbitmq-queue-management by gessnerfl.

the class MessageMapperTest method shouldMapRabbitMqSpecificTypesInAmqpBasicPropertiesHeadersDeepInLists.

@Test
public void shouldMapRabbitMqSpecificTypesInAmqpBasicPropertiesHeadersDeepInLists() {
    String headerKey = "headerKey";
    String listValue = "listValue";
    List<String> list = Arrays.asList(listValue);
    Map<String, Object> headers = new HashMap<>();
    headers.put(headerKey, list);
    AMQP.BasicProperties basicProperties = mock(AMQP.BasicProperties.class);
    when(basicProperties.getHeaders()).thenReturn(headers);
    Envelope envelope = mock(Envelope.class);
    GetResponse getResponse = mockResponse(envelope, basicProperties);
    Message result = sut.map(getResponse);
    BasicProperties basicPropertiesOfResult = result.getProperties();
    assertNotNull(basicPropertiesOfResult);
    assertThat(basicPropertiesOfResult.getHeaders().keySet(), Matchers.hasSize(1));
    assertThat(basicPropertiesOfResult.getHeaders(), Matchers.hasKey(headerKey));
    assertThat(basicPropertiesOfResult.getHeaders().get(headerKey), Matchers.instanceOf(List.class));
    assertThat(((List<String>) basicPropertiesOfResult.getHeaders().get(headerKey)), Matchers.hasSize(1));
    assertThat(((List<String>) basicPropertiesOfResult.getHeaders().get(headerKey)), Matchers.contains(listValue));
}
Also used : Message(de.gessnerfl.rabbitmq.queue.management.model.Message) AMQP(com.rabbitmq.client.AMQP) BasicProperties(de.gessnerfl.rabbitmq.queue.management.model.BasicProperties) LongString(com.rabbitmq.client.LongString) Envelope(com.rabbitmq.client.Envelope) GetResponse(com.rabbitmq.client.GetResponse) Test(org.junit.Test)

Example 22 with Envelope

use of com.rabbitmq.client.Envelope 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 23 with Envelope

use of com.rabbitmq.client.Envelope 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)

Example 24 with Envelope

use of com.rabbitmq.client.Envelope in project beam by apache.

the class RabbitMqMessage method serializableDeliveryOf.

/**
 * Make delivery serializable by cloning all non-serializable values into serializable ones. If it
 * is not possible, initial delivery is returned and error message is logged
 *
 * @param processed
 * @return
 */
private static GetResponse serializableDeliveryOf(GetResponse processed) {
    // All content of envelope is serializable, so no problem there
    Envelope envelope = processed.getEnvelope();
    // in basicproperties, there may be LongString, which are *not* serializable
    BasicProperties properties = processed.getProps();
    BasicProperties nextProperties = new BasicProperties.Builder().appId(properties.getAppId()).clusterId(properties.getClusterId()).contentEncoding(properties.getContentEncoding()).contentType(properties.getContentType()).correlationId(properties.getCorrelationId()).deliveryMode(properties.getDeliveryMode()).expiration(properties.getExpiration()).headers(serializableHeaders(properties.getHeaders())).messageId(properties.getMessageId()).priority(properties.getPriority()).replyTo(properties.getReplyTo()).timestamp(properties.getTimestamp()).type(properties.getType()).userId(properties.getUserId()).build();
    return new GetResponse(envelope, nextProperties, processed.getBody(), processed.getMessageCount());
}
Also used : BasicProperties(com.rabbitmq.client.AMQP.BasicProperties) Envelope(com.rabbitmq.client.Envelope) GetResponse(com.rabbitmq.client.GetResponse)

Example 25 with Envelope

use of com.rabbitmq.client.Envelope in project rabbitmq-java-client by rabbitmq.

the class TopologyRecoveryFiltering method topologyRecoveryFilteringConsumers.

@Test
public void topologyRecoveryFilteringConsumers() throws Exception {
    Channel ch = c.createChannel();
    ch.exchangeDeclare("topology.recovery.exchange", "direct");
    ch.queueDeclare("topology.recovery.queue.1", false, false, false, null);
    ch.queueDeclare("topology.recovery.queue.2", false, false, false, null);
    ch.queueBind("topology.recovery.queue.1", "topology.recovery.exchange", "recovered.consumer");
    ch.queueBind("topology.recovery.queue.2", "topology.recovery.exchange", "filtered.consumer");
    final AtomicInteger recoveredConsumerMessageCount = new AtomicInteger(0);
    ch.basicConsume("topology.recovery.queue.1", true, "recovered.consumer", new DefaultConsumer(ch) {

        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            recoveredConsumerMessageCount.incrementAndGet();
        }
    });
    ch.basicPublish("topology.recovery.exchange", "recovered.consumer", null, "".getBytes());
    waitAtMost(Duration.ofSeconds(5), () -> recoveredConsumerMessageCount.get() == 1);
    final AtomicInteger filteredConsumerMessageCount = new AtomicInteger(0);
    final CountDownLatch filteredConsumerLatch = new CountDownLatch(2);
    ch.basicConsume("topology.recovery.queue.2", true, "filtered.consumer", new DefaultConsumer(ch) {

        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            filteredConsumerMessageCount.incrementAndGet();
            filteredConsumerLatch.countDown();
        }
    });
    ch.basicPublish("topology.recovery.exchange", "filtered.consumer", null, "".getBytes());
    waitAtMost(Duration.ofSeconds(5), () -> filteredConsumerMessageCount.get() == 1);
    closeAndWaitForRecovery((RecoverableConnection) c);
    int initialCount = recoveredConsumerMessageCount.get();
    ch.basicPublish("topology.recovery.exchange", "recovered.consumer", null, "".getBytes());
    waitAtMost(Duration.ofSeconds(5), () -> recoveredConsumerMessageCount.get() == initialCount + 1);
    ch.basicPublish("topology.recovery.exchange", "filtered.consumer", null, "".getBytes());
    assertFalse("Consumer shouldn't recover, no extra messages should have been received", filteredConsumerLatch.await(5, TimeUnit.SECONDS));
}
Also used : DefaultConsumer(com.rabbitmq.client.DefaultConsumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AMQP(com.rabbitmq.client.AMQP) Channel(com.rabbitmq.client.Channel) IOException(java.io.IOException) Envelope(com.rabbitmq.client.Envelope) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Aggregations

Envelope (com.rabbitmq.client.Envelope)31 DefaultConsumer (com.rabbitmq.client.DefaultConsumer)20 AMQP (com.rabbitmq.client.AMQP)18 IOException (java.io.IOException)17 Channel (com.rabbitmq.client.Channel)16 Test (org.junit.Test)12 Connection (com.rabbitmq.client.Connection)11 ConnectionFactory (com.rabbitmq.client.ConnectionFactory)10 TimeoutException (java.util.concurrent.TimeoutException)9 GetResponse (com.rabbitmq.client.GetResponse)8 BasicProperties (com.rabbitmq.client.AMQP.BasicProperties)6 LongString (com.rabbitmq.client.LongString)5 Consumer (com.rabbitmq.client.Consumer)4 BasicProperties (de.gessnerfl.rabbitmq.queue.management.model.BasicProperties)4 Message (de.gessnerfl.rabbitmq.queue.management.model.Message)4 KeyManagementException (java.security.KeyManagementException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 UUID (java.util.UUID)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 Path (javax.ws.rs.Path)3