org.springframework.amqp.support.AmqpHeaders Java Examples

The following examples show how to use org.springframework.amqp.support.AmqpHeaders. 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: RabbitReceiver.java    From code with Apache License 2.0 7 votes vote down vote up
/**
 * 
 * 	spring.rabbitmq.listener.order.queue.name=queue-2
	spring.rabbitmq.listener.order.queue.durable=true
	spring.rabbitmq.listener.order.exchange.name=exchange-1
	spring.rabbitmq.listener.order.exchange.durable=true
	spring.rabbitmq.listener.order.exchange.type=topic
	spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions=true
	spring.rabbitmq.listener.order.key=springboot.*
 * @param order
 * @param channel
 * @param headers
 * @throws Exception
 */
@RabbitListener(bindings = @QueueBinding(
		value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}", 
		durable="${spring.rabbitmq.listener.order.queue.durable}"),
		exchange = @Exchange(value = "${spring.rabbitmq.listener.order.exchange.name}", 
		durable="${spring.rabbitmq.listener.order.exchange.durable}", 
		type= "${spring.rabbitmq.listener.order.exchange.type}", 
		ignoreDeclarationExceptions = "${spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions}"),
		key = "${spring.rabbitmq.listener.order.key}"
		)
)
@RabbitHandler
public void onOrderMessage(@Payload com.bfxy.springboot.entity.Order order, 
		Channel channel, 
		@Headers Map<String, Object> headers) throws Exception {
	System.err.println("--------------------------------------");
	System.err.println("消费端order: " + order.getId());
	Long deliveryTag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
	//手工ACK
	channel.basicAck(deliveryTag, false);
}
 
Example #2
Source File: AsyncRPCServer.java    From SpringBootBucket with MIT License 7 votes vote down vote up
@RabbitListener(queues = QUEUE_ASYNC_RPC_WITH_FIXED_REPLY)
    public void processAsyncRpcFixed(User user,
                                     @Header(AmqpHeaders.REPLY_TO) String replyTo,
                                     @Header(AmqpHeaders.CORRELATION_ID) byte[] correlationId) {
//        String body = new String(message.getBody(), Charset.forName("UTF-8"));
//        User user = JacksonUtil.json2Bean(body, new TypeReference<User>(){});
        logger.info("user.name={}", user.getName());
        logger.info("use a fixed reply queue={}, correlationId={}", replyTo, new String(correlationId));
        ListenableFuture<String> asyncResult = asyncTask.expensiveOperation(user.getName());
        asyncResult.addCallback(new ListenableFutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                amqpTemplate.convertAndSend(replyTo, (Object) result, m -> {
                    //https://stackoverflow.com/questions/42382307/messageproperties-setcorrelationidstring-is-not-working
                    m.getMessageProperties().setCorrelationId(new String(correlationId));
                    return m;
                });
            }

            @Override
            public void onFailure(Throwable ex) {
                logger.error("接受到QUEUE_ASYNC_RPC_WITH_FIXED_REPLY失败", ex);
            }
        });
    }
 
Example #3
Source File: RabbitReceiver.java    From code with Apache License 2.0 6 votes vote down vote up
@RabbitListener(bindings = @QueueBinding(
		value = @Queue(value = "queue-1", 
		durable="true"),
		exchange = @Exchange(value = "exchange-1", 
		durable="true", 
		type= "topic", 
		ignoreDeclarationExceptions = "true"),
		key = "springboot.*"
		)
)
@RabbitHandler
public void onMessage(Message message, Channel channel) throws Exception {
	System.err.println("--------------------------------------");
	System.err.println("消费端Payload: " + message.getPayload());
	Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
	//手工ACK
	channel.basicAck(deliveryTag, false);
}
 
Example #4
Source File: AsyncRPCServer.java    From SpringBootBucket with MIT License 6 votes vote down vote up
@RabbitListener(queues = QUEUE_ASYNC_RPC)
public void processAsyncRpc(Message message, @Header(AmqpHeaders.REPLY_TO) String replyTo) {
    String body = new String(message.getBody(), Charset.forName("UTF-8"));
 User user = JacksonUtil.json2Bean(body, new TypeReference<User>(){});
    logger.info("recevie message {} and reply to {}, user.name={}", body, replyTo, user.getName());
    if (replyTo.startsWith("amq.rabbitmq.reply-to")) {
        logger.debug("starting with version 3.4.0, the RabbitMQ server now supports Direct reply-to");
    } else {
        logger.info("fall back to using a temporary reply queue");
    }
    ListenableFuture<String> asyncResult = asyncTask.expensiveOperation(body);
    asyncResult.addCallback(new ListenableFutureCallback<String>() {
        @Override
        public void onSuccess(String result) {
            amqpTemplate.convertAndSend(replyTo, result);
        }

        @Override
        public void onFailure(Throwable ex) {
            logger.error("接受到QUEUE_ASYNC_RPC失败", ex);
        }
    });
}
 
Example #5
Source File: SpringAmqpStubMessages.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Override
public <T> void send(T payload, Map<String, Object> headers, String destination) {
	Message message = org.springframework.amqp.core.MessageBuilder
			.withBody(((String) payload).getBytes())
			.andProperties(MessagePropertiesBuilder.newInstance()
					.setContentType(header(headers, "contentType"))
					.copyHeaders(headers).build())
			.build();
	if (headers != null && headers.containsKey(DEFAULT_CLASSID_FIELD_NAME)) {
		message.getMessageProperties().setHeader(DEFAULT_CLASSID_FIELD_NAME,
				headers.get(DEFAULT_CLASSID_FIELD_NAME));
	}
	if (headers != null && headers.containsKey(AmqpHeaders.RECEIVED_ROUTING_KEY)) {
		message.getMessageProperties().setReceivedRoutingKey(
				header(headers, AmqpHeaders.RECEIVED_ROUTING_KEY));
	}
	send(message, destination);
}
 
Example #6
Source File: RabbitmqReceiver.java    From code with Apache License 2.0 5 votes vote down vote up
@StreamListener(Barista.INPUT_CHANNEL)  
  public void receiver(Message message) throws Exception {  
Channel channel = (com.rabbitmq.client.Channel) message.getHeaders().get(AmqpHeaders.CHANNEL);
Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
  	System.out.println("Input Stream 1 接受数据:" + message);
  	System.out.println("消费完毕------------");
  	channel.basicAck(deliveryTag, false);
  }
 
Example #7
Source File: LocalListner.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to process messages from queue.
 * 
 * @param in
 * @param channel
 * @param tag
 * @throws IOException
 * @throws InterruptedException
 */
@RabbitListener(queues = "espm.salesOrders")
public void recieve(SalesOrder in, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag)
		throws IOException, InterruptedException {

	SalesOrderRepository repo = appContext.getBean(SalesOrderRepository.class);
	try {
		if (!repo.existsById(in.getSalesOrderId())) {
			repo.save(in);
			logger.info(in.getSalesOrderId() + " created");
			channel.basicAck(tag, false);
			value = initialValue;

		} else {
			logger.error(in.getSalesOrderId() + " already Exists, Deleting from Queue");
			channel.basicAck(tag, false);

		}
	} catch (DataIntegrityViolationException e) {
		logger.error(in.getSalesOrderId() + " is an invalid Sales-Order, Deleting from Queue");
		channel.basicNack(tag, false, false);

	} catch (CannotCreateTransactionException ccte) {
		logger.error("Unable to connect to DB");
		logger.error("Backing  for " + value);
		TimeUnit.MILLISECONDS.sleep(value);
		if (value <= maxVal)
			value = value * multiplier;
		channel.basicNack(tag, false, true);

	}

}
 
Example #8
Source File: MessageAckListener.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@StreamListener(TestSourceInput.INPUT)
    public void receive(Object msg, @Header(AmqpHeaders.CHANNEL) Channel channel,
                        @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        log.info("Received3:" + msg);
        boolean request = false;//true=重新发送
//        channel.basicReject(deliveryTag, request);
        channel.basicAck(deliveryTag, false);
    }
 
Example #9
Source File: OrderConsumer2.java    From SpringBoot-Course with MIT License 5 votes vote down vote up
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "order_direct_exchange", durable = "true"),
        exchange = @Exchange(value = "order_direct_queue", durable = "true", type = "direct", ignoreDeclarationExceptions = "true"),
        key = "order_routingKey"
))
@RabbitHandler
public void onMessage(Message message, Channel channel) throws Exception {
    System.err.println("OrderConusmer2: " + message.getPayload());

    Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);

    channel.basicAck(deliveryTag, false);
}
 
Example #10
Source File: RabbitSourceTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
	Advice[] adviceChain = TestUtils.getPropertyValue(this.container, "adviceChain", Advice[].class);
	assertEquals(1, adviceChain.length);
	RetryTemplate retryTemplate = TestUtils.getPropertyValue(adviceChain[0], "retryOperations",
			RetryTemplate.class);
	assertEquals(5, TestUtils.getPropertyValue(retryTemplate, "retryPolicy.maxAttempts"));
	assertEquals(123L, TestUtils.getPropertyValue(retryTemplate, "backOffPolicy.initialInterval"));
	assertEquals(345L, TestUtils.getPropertyValue(retryTemplate, "backOffPolicy.maxInterval"));
	assertEquals(1.5, TestUtils.getPropertyValue(retryTemplate, "backOffPolicy.multiplier"));
	assertEquals("scsapp-testq", this.container.getQueueNames()[0]);
	assertFalse(TestUtils.getPropertyValue(this.container, "defaultRequeueRejected", Boolean.class));
	assertEquals(2, TestUtils.getPropertyValue(this.container, "concurrentConsumers"));
	assertEquals(3, TestUtils.getPropertyValue(this.container, "maxConcurrentConsumers"));
	assertEquals(AcknowledgeMode.NONE, TestUtils.getPropertyValue(this.container, "acknowledgeMode"));
	assertEquals(10, TestUtils.getPropertyValue(this.container, "prefetchCount"));
	assertEquals(5, TestUtils.getPropertyValue(this.container, "txSize"));

	this.rabbitTemplate.convertAndSend("", "scsapp-testq", "foo", new MessagePostProcessor() {

		@Override
		public org.springframework.amqp.core.Message postProcessMessage(
				org.springframework.amqp.core.Message message) throws AmqpException {
			message.getMessageProperties().getHeaders().put("bar", "baz");
			return message;
		}

	});
	Message<?> out = this.messageCollector.forChannel(this.channels.output()).poll(10,  TimeUnit.SECONDS);
	assertNotNull(out);
	assertEquals("foo", out.getPayload());
	assertEquals("baz", out.getHeaders().get("bar"));
	assertNull(out.getHeaders().get(AmqpHeaders.DELIVERY_MODE));
}
 
Example #11
Source File: RabbitSinkTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
	this.channels.input().send(MessageBuilder.withPayload("foo")
								.setHeader("bar", "baz")
								.setHeader(AmqpHeaders.DELIVERY_MODE, MessageDeliveryMode.PERSISTENT)
								.build());
	this.rabbitTemplate.setReceiveTimeout(10000);
	Message received = this.rabbitTemplate.receive("scsapp-testq");
	assertEquals("\"foo\"", new String(received.getBody()));
	assertEquals("baz", received.getMessageProperties().getHeaders().get("bar"));
	assertEquals(MessageDeliveryMode.PERSISTENT, received.getMessageProperties().getDeliveryMode());
	assertSame(this.myConverter, this.rabbitTemplate.getMessageConverter());
}
 
Example #12
Source File: TracingChannelInterceptorTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void should_store_rabbitmq_as_remote_service_name_when_rabbit_header_is_present() {
	ExecutorSubscribableChannel channel = new ExecutorSubscribableChannel();
	channel.addInterceptor(this.interceptor);
	List<Message<?>> messages = new ArrayList<>();
	channel.subscribe(messages::add);

	Map<String, Object> headers = new HashMap<>();
	headers.put(AmqpHeaders.RECEIVED_ROUTING_KEY, "hello");
	channel.send(MessageBuilder.createMessage("foo", new MessageHeaders(headers)));

	assertThat(this.spans).extracting(MutableSpan::remoteServiceName)
			.contains("rabbitmq");
}
 
Example #13
Source File: PartitioningRabbitDemoApplication.java    From spring-cloud-stream-samples with Apache License 2.0 4 votes vote down vote up
@Bean
public Consumer<Message<String>> listen() {
	return message -> logger.info(message.getPayload() + " received from partition "
			+ message.getHeaders().get(AmqpHeaders.CONSUMER_QUEUE));
}
 
Example #14
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testBatchingAndCompression() throws Exception {
	RabbitTestBinder binder = getBinder();
	ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
	producerProperties.getExtension()
			.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
	producerProperties.getExtension().setBatchingEnabled(true);
	producerProperties.getExtension().setBatchSize(2);
	producerProperties.getExtension().setBatchBufferLimit(100000);
	producerProperties.getExtension().setBatchTimeout(30000);
	producerProperties.getExtension().setCompress(true);
	producerProperties.setRequiredGroups("default");

	DirectChannel output = createBindableChannel("output",
			createProducerBindingProperties(producerProperties));
	output.setBeanName("batchingProducer");
	Binding<MessageChannel> producerBinding = binder.bindProducer("batching.0",
			output, producerProperties);

	Log logger = spy(TestUtils.getPropertyValue(binder,
			"binder.compressingPostProcessor.logger", Log.class));
	new DirectFieldAccessor(
			TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor"))
					.setPropertyValue("logger", logger);
	when(logger.isTraceEnabled()).thenReturn(true);

	assertThat(TestUtils.getPropertyValue(binder,
			"binder.compressingPostProcessor.level")).isEqualTo(Deflater.BEST_SPEED);

	output.send(new GenericMessage<>("foo".getBytes()));
	output.send(new GenericMessage<>("bar".getBytes()));

	Object out = spyOn("batching.0.default").receive(false);
	assertThat(out).isInstanceOf(byte[].class);
	assertThat(new String((byte[]) out))
			.isEqualTo("\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar");

	ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
	verify(logger).trace(captor.capture());
	assertThat(captor.getValue().toString()).contains(("Compressed 14 to "));

	QueueChannel input = new QueueChannel();
	input.setBeanName("batchingConsumer");
	Binding<MessageChannel> consumerBinding = binder.bindConsumer("batching.0",
			"test", input, createConsumerProperties());

	output.send(new GenericMessage<>("foo".getBytes()));
	output.send(new GenericMessage<>("bar".getBytes()));

	Message<byte[]> in = (Message<byte[]>) input.receive(10000);
	assertThat(in).isNotNull();
	assertThat(new String(in.getPayload())).isEqualTo("foo");
	in = (Message<byte[]>) input.receive(10000);
	assertThat(in).isNotNull();
	assertThat(new String(in.getPayload())).isEqualTo("bar");
	assertThat(in.getHeaders().get(AmqpHeaders.DELIVERY_MODE)).isNull();

	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example #15
Source File: ElasticsearchListener.java    From jakduk-api with MIT License 4 votes vote down vote up
@RabbitListener(queues = "${jakduk.rabbitmq.queues.elasticsearch.binding-queue-name}")
public void receive(Message message, @Header(AmqpHeaders.RECEIVED_ROUTING_KEY) String routingKey) throws IOException {

    String findKey = rabbitmqProperties.getRoutingKeys().entrySet().stream()
            .filter(entity -> entity.getValue().equals(routingKey))
            .findFirst()
            .map(Map.Entry::getKey)
            .orElseThrow(() -> new ServiceException(ServiceError.ILLEGAL_ARGUMENT));

    ElasticsearchRoutingKey elasticsearchRoutingKey = ElasticsearchRoutingKey.find(findKey);

    switch (elasticsearchRoutingKey) {
        case ELASTICSEARCH_INDEX_DOCUMENT_ARTICLE:
            EsArticle esArticle = ObjectMapperUtils.readValue(message.getBody(), EsArticle.class);
            searchService.indexDocumentArticle(esArticle);
            break;

            case ELASTICSEARCH_DELETE_DOCUMENT_ARTICLE:
            String boardId = ObjectMapperUtils.readValue(message.getBody(), String.class);
                searchService.deleteDocumentBoard(boardId);
            break;

        case ELASTICSEARCH_INDEX_DOCUMENT_ARTICLE_COMMENT:
            EsComment esComment = ObjectMapperUtils.readValue(message.getBody(), EsComment.class);
            searchService.indexDocumentBoardComment(esComment);
            break;

        case ELASTICSEARCH_DELETE_DOCUMENT_ARTICLE_COMMENT:
            String commentId = ObjectMapperUtils.readValue(message.getBody(), String.class);
            searchService.deleteDocumentBoardComment(commentId);
            break;

        case ELASTICSEARCH_INDEX_DOCUMENT_GALLERY:
            EsGallery esGallery = ObjectMapperUtils.readValue(message.getBody(), EsGallery.class);
            searchService.indexDocumentGallery(esGallery);
            break;

        case ELASTICSEARCH_DELETE_DOCUMENT_GALLERY:
            String galleryId = ObjectMapperUtils.readValue(message.getBody(), String.class);
            searchService.deleteDocumentGallery(galleryId);
            break;

        case ELASTICSEARCH_INDEX_DOCUMENT_SEARCH_WORD:
            EsSearchWord esSearchWord = ObjectMapperUtils.readValue(message.getBody(), EsSearchWord.class);
            searchService.indexDocumentSearchWord(esSearchWord);
            break;

    }
}