Java Code Examples for com.rabbitmq.client.AMQP#BasicProperties

The following examples show how to use com.rabbitmq.client.AMQP#BasicProperties . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MyConsumer.java    From SpringBoot-Course with MIT License 6 votes vote down vote up
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    super.handleDelivery(consumerTag, envelope, properties, body);

    String message = new String(body, "UTF-8");
    System.out.printf("in consumer B (delivery tag is %d): %s\n", envelope.getDeliveryTag(), message);

    try {
        TimeUnit.MILLISECONDS.sleep(2000);
    } catch (InterruptedException e) {

    }

    // 第二个参数为 false 表示不批量签收
    channel.basicAck(envelope.getDeliveryTag(), false);
}
 
Example 2
Source File: DeadLettering.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public AMQP.BasicProperties prependOn(AMQP.BasicProperties props) {
    Map<String, Object> headers = Optional.ofNullable(props.getHeaders()).map(HashMap::new).orElseGet(HashMap::new);

    List<Map<String, Object>> xDeathHeader = (List<Map<String, Object>>) headers.computeIfAbsent(X_DEATH_HEADER, key -> new ArrayList<>());

    Optional<Map<String, Object>> previousEvent = xDeathHeader.stream()
        .filter(this::sameQueueAndReason)
        .findFirst();

    final Map<String, Object> currentEvent;
    if (previousEvent.isPresent()) {
        xDeathHeader.remove(previousEvent.get());
        currentEvent = incrementCount(previousEvent.get());
    } else {
        currentEvent = asHeaderEntry();
    }
    xDeathHeader.add(0, currentEvent);

    return props.builder().headers(Collections.unmodifiableMap(headers)).build();
}
 
Example 3
Source File: MockQueue.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
public boolean publish(String exchangeName, String routingKey, AMQP.BasicProperties props, byte[] body) {
    boolean queueLengthLimitReached = queueLengthLimitReached() || queueLengthBytesLimitReached();
    if (queueLengthLimitReached && arguments.overflow() == AmqArguments.Overflow.REJECT_PUBLISH) {
        return true;
    }
    Message message = new Message(
        messageSequence.incrementAndGet(),
        exchangeName,
        routingKey,
        props,
        body,
        computeExpiryTime(props)
    );
    if (message.expiryTime != -1) {
        LOGGER.debug(localized("Message published expiring at " + Instant.ofEpochMilli(message.expiryTime)) + ": " + message);
    } else {
        LOGGER.debug(localized("Message published" + ": " + message));
    }
    messages.offer(message);
    if (queueLengthLimitReached) {
        deadLetterWithReason(messages.poll(), DeadLettering.ReasonType.MAX_LEN);
    }
    return true;
}
 
Example 4
Source File: C.java    From java-study with Apache License 2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
		// 创建连接工厂
		ConnectionFactory factory = new ConnectionFactory();
//		设置RabbitMQ地址
		factory.setHost("127.0.0.1");
//		创建一个新的连接
		Connection connection = factory.newConnection();
//		创建一个频道
		Channel channel = connection.createChannel();
//		声明要关注的队列 -- 在RabbitMQ中,队列声明是幂等性的(一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同),也就是说,如果不存在,就创建,如果存在,不会对已经存在的队列产生任何影响。
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		System.out.println("C [*] Waiting for messages. To exit press CTRL+C");
//		DefaultConsumer类实现了Consumer接口,通过传入一个频道,告诉服务器我们需要那个频道的消息,如果频道中有消息,就会执行回调函数handleDelivery
		Consumer consumer = new DefaultConsumer(channel) {
			@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("C [x] Received '" + message + "'");
			}
		};
//		自动回复队列应答 -- RabbitMQ中的消息确认机制
		channel.basicConsume(QUEUE_NAME, true, consumer);
	}
 
Example 5
Source File: MyConsumer.java    From code with Apache License 2.0 6 votes vote down vote up
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    System.err.println("-----------consume message----------");
    System.err.println("body: " + new String(body));
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    if ((Integer) properties.getHeaders().get("num") == 0) {
        // noack 重回队列
        channel.basicNack(envelope.getDeliveryTag(), false, true);
    } else {
        channel.basicAck(envelope.getDeliveryTag(), false);
    }

}
 
Example 6
Source File: BindableMockExchange.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Override
public boolean publish(String previousExchangeName, String routingKey, AMQP.BasicProperties props, byte[] body) {
    Set<Receiver> matchingReceivers = matchingReceivers(routingKey, props)
        .map(receiverRegistry::getReceiver)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toSet());

    if (matchingReceivers.isEmpty()) {
        return getAlternateExchange().map(e -> {
            LOGGER.debug(localized("message to alternate " + e));
            return e.publish(name, routingKey, props, body);
        }).orElse(false);
    } else {
        matchingReceivers
            .forEach(e -> {
                LOGGER.debug(localized("message to " + e));
                e.publish(name, routingKey, props, body);
            });
        return true;
    }
}
 
Example 7
Source File: ExtensionTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void message_ttl_in_publishers_reject_messages_after_expiration_is_reached() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            channel.queueDeclare("fruits", true, false, false, null);
            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .expiration("200")
                .build();
            channel.basicPublish("", "fruits", properties, "banana".getBytes());
            TimeUnit.MILLISECONDS.sleep(400L);
            GetResponse getResponse = channel.basicGet("fruits", true);
            assertThat(getResponse).isNull();
        }
    }
}
 
Example 8
Source File: RabbitMQConsumer.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Called when a basic.deliver is received for this consumer.
 *
 * @param consumerTag the consumer tag associated with the consumer
 * @param envelope    packaging data for the message
 * @param properties  content header data for the message
 * @param body        the message body (opaque, client-specific byte array)
 * @throws IOException if the consumer encounters an I/O error while processing the message
 * @see Envelope
 */
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
        throws IOException {
    boolean successful = injectHandler.onMessage(properties, body, inboundName);
    if (successful) {
        if (!autoAck) {
            channel.basicAck(envelope.getDeliveryTag(), false);
        }
    } else {
        List<HashMap<String, Object>> xDeathHeader =
                (ArrayList<HashMap<String, Object>>) properties.getHeaders().get("x-death");
        // check if message has been already dead-lettered
        if (xDeathHeader != null && xDeathHeader.size() > 0 && maxDeadLetteredCount != -1) {
            Long count = (Long) xDeathHeader.get(0).get("count");
            if (count <= maxDeadLetteredCount) {
                channel.basicReject(envelope.getDeliveryTag(), false);
                log.info("The rejected message with message id: " + properties.getMessageId() + " and " +
                        "delivery tag: " + envelope.getDeliveryTag() + " on the queue: " + queueName + " is " +
                        "dead-lettered " + count + " time(s).");
            } else {
                // handle the message after exceeding the max dead-lettered count
                proceedAfterMaxDeadLetteredCount(envelope, properties, body);
            }
        } else {
            // the message might be dead-lettered or discard if an error occurred in the mediation flow
            channel.basicReject(envelope.getDeliveryTag(), false);
            log.info("The rejected message with message id: " + properties.getMessageId() + " and " +
                    "delivery tag: " + envelope.getDeliveryTag() + " on the queue: " + queueName + " will " +
                    "discard or dead-lettered.");
        }
    }
}
 
Example 9
Source File: Message.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
private Message(int id, String exchangeName, String routingKey, AMQP.BasicProperties props, byte[] body, long expiryTime, boolean redelivered) {
    this.id = id;
    this.exchangeName = exchangeName;
    this.routingKey = routingKey;
    this.props = props;
    this.body = body;
    this.expiryTime = expiryTime;
    this.redelivered = redelivered;
}
 
Example 10
Source File: Transaction.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
private PublishedMessage(String exchange, String routingKey, boolean mandatory, boolean immediate, AMQP.BasicProperties props, byte[] body) {
    this.exchange = exchange;
    this.routingKey = routingKey;
    this.mandatory = mandatory;
    this.immediate = immediate;
    this.props = props;
    this.body = body;
}
 
Example 11
Source File: RabbitMQAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static AMQP.BasicProperties enterPublish(final Object exchange, final Object routingKey, final Object props) {
  final AMQP.BasicProperties properties = (AMQP.BasicProperties)props;
  final Tracer tracer = GlobalTracer.get();
  final Span span = TracingUtils.buildSpan((String)exchange, (String)routingKey, properties, tracer);

  final Scope scope = tracer.activateSpan(span);
  LocalSpanContext.set(SpanDecorator.COMPONENT_NAME, span, scope);

  return inject(properties, span, tracer);
}
 
Example 12
Source File: ExtensionTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void non_long_message_ttl_in_publishers_is_not_used() throws IOException, TimeoutException, InterruptedException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            channel.queueDeclare("fruits", true, false, false, null);
            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                .expiration("test")
                .build();
            channel.basicPublish("", "fruits", properties, "banana".getBytes());
            TimeUnit.MILLISECONDS.sleep(100L);
            GetResponse getResponse = channel.basicGet("fruits", true);
            assertThat(getResponse).isNotNull();
        }
    }
}
 
Example 13
Source File: MyConsumer.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    System.err.println("-----------consume message----------");
    System.err.println("consumerTag: " + consumerTag);
    System.err.println("envelope: " + envelope);
    System.err.println("properties: " + properties);
    System.err.println("body: " + new String(body));

    //channel.basicAck(envelope.getDeliveryTag(), false);

}
 
Example 14
Source File: MyConsumer.java    From SpringBoot-Course with MIT License 5 votes vote down vote up
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    super.handleDelivery(consumerTag, envelope, properties, body);

    String message = new String(body, "UTF-8");
    System.out.printf("in consumer B (delivery tag is %d): %s\n", envelope.getDeliveryTag(), message);

    try {
        TimeUnit.MILLISECONDS.sleep(200);
    } catch (InterruptedException e) {

    }

    //channel.basicAck(envelope.getDeliveryTag(), false);
}
 
Example 15
Source File: MockChannel.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
private AMQP.BasicProperties nullToEmpty(AMQP.BasicProperties props) {
    return props != null ? props : new AMQP.BasicProperties.Builder().build();
}
 
Example 16
Source File: ExtensionTest.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
@Test
void check_xdeath_header_count_increments_for_the_same_q_and_reason() throws IOException, TimeoutException, InterruptedException {
    try (MockConnection conn = new MockConnectionFactory().newConnection()) {
        try (MockChannel channel = conn.createChannel()) {

            Semaphore se = new Semaphore(0);

            QueueDeclarator.queue("timed").withMessageTtl(1L).withDeadLetterExchange("rejected-ex").declare(channel);
            QueueDeclarator.queue("fruits").withDeadLetterExchange("rejected-ex").declare(channel);
            channel.exchangeDeclare("rejected-ex", BuiltinExchangeType.FANOUT);
            channel.queueBindNoWait("fruits", "rejected-ex", "unused", null);

            AtomicInteger nackCounter = new AtomicInteger();
            AtomicReference<AMQP.BasicProperties> messagePropertiesAfterMultipleReject = new AtomicReference<>();

            channel.basicConsume("fruits", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) {
                    if (nackCounter.incrementAndGet() <= 4) {
                        channel.basicNack(envelope.getDeliveryTag(), false, false);
                    } else {
                        channel.basicAck(envelope.getDeliveryTag(), false);
                        messagePropertiesAfterMultipleReject.set(properties);
                        se.release();
                    }
                }
            });

            channel.basicPublish("", "timed", null, "banana".getBytes());

            se.acquire();

            assertThat(messagePropertiesAfterMultipleReject.get().getHeaders()).containsKey("x-death");
            List<Map<String, Object>> xDeathHeader = (List<Map<String, Object>>) messagePropertiesAfterMultipleReject.get().getHeaders().get("x-death");
            assertThat(xDeathHeader).hasSize(2);
            assertThat(xDeathHeader.get(0))
                .containsEntry("queue", "fruits")
                .containsEntry("reason", "rejected")
                .containsEntry("exchange", "rejected-ex")
                .containsEntry("routing-keys", Collections.singletonList("timed"))
                .containsEntry("count", 4L)
            ;
            assertThat(xDeathHeader.get(1))
                .containsEntry("queue", "timed")
                .containsEntry("reason", "expired")
                .containsEntry("exchange", "")
                .containsEntry("routing-keys", Collections.singletonList("timed"))
                .containsEntry("count", 1L)
            ;
        }
    }
}
 
Example 17
Source File: MockQueue.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
private Optional<Long> getMessageExpiryTime(AMQP.BasicProperties props) {
    return Optional.ofNullable(props.getExpiration())
        .flatMap(this::toLong)
        .map(this::computeExpiry);
}
 
Example 18
Source File: ConsistentHashExchange.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
@Override
protected Optional<ReceiverPointer> selectReceiver(String routingKey, AMQP.BasicProperties props) {
    int bucketSelector = Math.abs(routingKey.hashCode()) % buckets.size();
    return Optional.of(buckets.get(bucketSelector).receiverPointer);
}
 
Example 19
Source File: Receiver.java    From rabbitmq-mock with Apache License 2.0 2 votes vote down vote up
/**
 * @return true if message got routed, false otherwise
 */
boolean publish(String exchangeName, String routingKey, AMQP.BasicProperties props, byte[] body);
 
Example 20
Source File: TransactionalOperations.java    From rabbitmq-mock with Apache License 2.0 votes vote down vote up
boolean basicPublish(String exchange, String routingKey, boolean mandatory, boolean immediate, AMQP.BasicProperties props, byte[] body);