org.springframework.amqp.core.MessageDeliveryMode Java Examples

The following examples show how to use org.springframework.amqp.core.MessageDeliveryMode. 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: RabbitTemplateMessageQueue.java    From elasticactors with Apache License 2.0 6 votes vote down vote up
private MessageProperties createProps(InternalMessage message) {
    MessageBuilderSupport<MessageProperties> messageBuilderSupport =
            MessagePropertiesBuilder.newInstance()
                    .setContentType(MessageProperties.CONTENT_TYPE_BYTES)
                    .setDeliveryMode(message.isDurable()
                            ? MessageDeliveryMode.PERSISTENT
                            : MessageDeliveryMode.NON_PERSISTENT);
    if (message.getTimeout() < 0) {
        return messageBuilderSupport.build();
    } else {
        return messageBuilderSupport
                .setPriority(MessageProperties.DEFAULT_PRIORITY)
                .setExpiration(String.valueOf(message.getTimeout()))
                .build();
    }
}
 
Example #2
Source File: RabbitSinkConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@ServiceActivator(inputChannel = Sink.INPUT)
@Bean
public MessageHandler amqpChannelAdapter(ConnectionFactory rabbitConnectionFactory) {
	AmqpOutboundEndpoint handler = new AmqpOutboundEndpoint(rabbitTemplate(rabbitConnectionFactory));
	DefaultAmqpHeaderMapper mapper = new DefaultAmqpHeaderMapper();
	mapper.setRequestHeaderNames(this.properties.getMappedRequestHeaders());
	handler.setHeaderMapper(mapper);
	handler.setDefaultDeliveryMode(this.properties.getPersistentDeliveryMode()
									? MessageDeliveryMode.PERSISTENT
									: MessageDeliveryMode.NON_PERSISTENT);
	if (this.properties.getExchangeExpression() == null) {
		handler.setExchangeName(this.properties.getExchange());
	}
	else {
		handler.setExpressionExchangeName(this.properties.getExchangeExpression());
	}
	if (this.properties.getRoutingKeyExpression() == null) {
		handler.setRoutingKey(this.properties.getRoutingKey());
	}
	else {
		handler.setExpressionRoutingKey(this.properties.getRoutingKeyExpression());
	}
	return handler;
}
 
Example #3
Source File: NotifyServiceImpl.java    From fw-cloud-framework with MIT License 5 votes vote down vote up
@Override
public void notifyPayOrder(NotifyBean notifyBean, int count) {
	rabbitTemplate.convertAndSend(RabbitConfiguration.PAY_NOTIFY_DELAY_PRE_MESSAGE_TTL,
			notifyBean, new MessagePostProcessor() {

				@Override
				public Message postProcessMessage(Message message) throws AmqpException {
					message.getMessageProperties().setExpiration(count + "");
					message.getMessageProperties().setDeliveryMode(
							MessageDeliveryMode.PERSISTENT);
					return message;
				}
			});
}
 
Example #4
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("qux", "fiz")
								.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("fiz", received.getMessageProperties().getHeaders().get("qux"));
	assertEquals(MessageDeliveryMode.NON_PERSISTENT, received.getMessageProperties().getDeliveryMode());
}
 
Example #5
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 #6
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("qux", "fiz")
								.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"));
	assertNull(received.getMessageProperties().getHeaders().get("qux"));
	assertEquals(MessageDeliveryMode.PERSISTENT, received.getMessageProperties().getDeliveryMode());
	assertThat(this.rabbitTemplate.getMessageConverter(), instanceOf(SimpleMessageConverter.class));
}
 
Example #7
Source File: AmqpReporter.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private void processMessageProperties(MessageProperties messageProperties) {
    messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
    messageProperties.setContentEncoding("UTF-8");
    messageProperties.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
    messageProperties.setHeader(MessageHeaders.HOST, OSUtils.getHostName());
    messageProperties.setAppId(AppInfo.getApplicationName());
    if(this.messagePropertiesCallback != null) {
        this.messagePropertiesCallback.call(messageProperties);
    }
}
 
Example #8
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomBatchingStrategy() throws Exception {
	RabbitTestBinder binder = getBinder();
	ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
	producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
	producerProperties.getExtension().setBatchingEnabled(true);
	producerProperties.getExtension().setBatchingStrategyBeanName("testCustomBatchingStrategy");
	producerProperties.setRequiredGroups("default");

	ConfigurableListableBeanFactory beanFactory = binder.getApplicationContext().getBeanFactory();
	beanFactory.registerSingleton("testCustomBatchingStrategy", new TestBatchingStrategy());

	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<>("0".getBytes()));
	output.send(new GenericMessage<>("1".getBytes()));
	output.send(new GenericMessage<>("2".getBytes()));
	output.send(new GenericMessage<>("3".getBytes()));
	output.send(new GenericMessage<>("4".getBytes()));

	Object out = spyOn("batching.0.default").receive(false);
	assertThat(out).isInstanceOf(byte[].class);
	assertThat(new String((byte[]) out)).isEqualTo("0\u0000\n1\u0000\n2\u0000\n3\u0000\n4\u0000\n");

	producerBinding.unbind();
}
 
Example #9
Source File: RabbitmqTemplate.java    From shine-mq with Apache License 2.0 5 votes vote down vote up
private Object sendWithEM(EventMessage eventMessage, int expiration, int priority, SendTypeEnum type) throws Exception {

        Object obj = null;
        MessageProperties messageProperties = new MessageProperties();
        //过期时间
        if (expiration > 0) {
            messageProperties.setExpiration(String.valueOf(expiration));
        }
        //消息优先级
        if (priority > 0) {
            messageProperties.setPriority(priority);
        }
        messageProperties.setMessageId(eventMessage.getMessageId());
        // 设置消息持久化
        messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
        Message message = messageConverter.toMessage(eventMessage, messageProperties);
        rabbitmqFactory.setCorrelationData(eventMessage.getMessageId(), eventMessage.getCoordinator(), eventMessage, null);
        try {
            if (SendTypeEnum.RPC.equals(type)) {
                obj = eventAmqpTemplate.convertSendAndReceive(eventMessage.getRoutingKey(), message);
            } else {
                eventAmqpTemplate.send(eventMessage.getExchangeName(), eventMessage.getRoutingKey(), message);
            }
        } catch (AmqpException e) {
            logger.error("send event fail. Event Message : [{}]", eventMessage, e);
            throw new Exception("send event fail", e);
        }
        return obj;
    }
 
Example #10
Source File: RabbitmqTemplate.java    From shine-mq with Apache License 2.0 5 votes vote down vote up
private Object send(String exchangeName, Object msg, MessageConverter messageConverter, SendTypeEnum type,
                    String routingKey, int expiration, int priority) throws Exception {
    check(exchangeName, routingKey);

    Object obj = null;
    String msgId = UUID.randomUUID().toString();
    EventMessage eventMessage = new EventMessage(exchangeName, routingKey, type.toString(), msg, null, msgId);
    MessageProperties messageProperties = new MessageProperties();
    //过期时间
    if (expiration > 0) {
        messageProperties.setExpiration(String.valueOf(expiration));
    }
    //消息优先级
    if (priority > 0) {
        messageProperties.setPriority(priority);
    }
    messageProperties.setMessageId(msgId);
    // 设置消息持久化
    messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
    Message message = messageConverter.toMessage(eventMessage, messageProperties);
    rabbitmqFactory.setCorrelationData(msgId, null, eventMessage, null);
    try {
        if (SendTypeEnum.RPC.equals(type)) {
            obj = eventAmqpTemplate.convertSendAndReceive(routingKey, message);
        } else {
            eventAmqpTemplate.send(exchangeName, routingKey, message);
        }
    } catch (AmqpException e) {
        logger.error("send event fail. Event Message : [{}]", eventMessage, e);
        throw new Exception("send event fail", e);
    }
    return obj;
}
 
Example #11
Source File: RabbitMessageProducer.java    From gpmall with Apache License 2.0 5 votes vote down vote up
public void send(String context) {
	//将订单发送到rabbitmq
	rabbitTemplate.convertAndSend(RabbitMqConfig.DELAY_EXCHANGE, context, message -> {
		message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
		message.getMessageProperties().setDelay(10 * 60 * 1000);//毫秒为单位
		return message;
	});
}
 
Example #12
Source File: RabbitConsumerProperties.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
public MessageDeliveryMode getRepublishDeliveyMode() {
	return this.republishDeliveyMode;
}
 
Example #13
Source File: RabbitConsumerProperties.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
public void setRepublishDeliveyMode(MessageDeliveryMode republishDeliveyMode) {
	this.republishDeliveyMode = republishDeliveyMode;
}
 
Example #14
Source File: RabbitProducerProperties.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
public void setDeliveryMode(MessageDeliveryMode deliveryMode) {
	this.deliveryMode = deliveryMode;
}
 
Example #15
Source File: RabbitProducerProperties.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
public MessageDeliveryMode getDeliveryMode() {
	return deliveryMode;
}
 
Example #16
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 testConsumerBatching() 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);

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

	QueueChannel input = new QueueChannel();
	input.setBeanName("batchingConsumer");
	ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
	consumerProperties.setBatchMode(true);
	consumerProperties.getExtension().setBatchSize(2);
	Binding<MessageChannel> consumerBinding = binder.bindConsumer("c.batching.0",
			"consumerBatching", input, consumerProperties);
	output.send(new GenericMessage<>("foo".getBytes()));
	output.send(new GenericMessage<>("bar".getBytes()));


	Message<?> in = input.receive(10000);
	assertThat(in).isNotNull();
	assertThat(in.getPayload()).isInstanceOf(List.class);
	List<byte[]> payload = (List<byte[]>) in.getPayload();
	assertThat(payload).hasSize(2);
	assertThat(payload.get(0)).isEqualTo("foo".getBytes());
	assertThat(payload.get(1)).isEqualTo("bar".getBytes());

	producerBinding.unbind();
	consumerBinding.unbind();
}
 
Example #17
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();
}