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));
}
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();
}
}
}
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);
}
}
}
}
}
});
}
}
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());
}
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));
}
Aggregations