org.springframework.integration.acks.AcknowledgmentCallback Java Examples

The following examples show how to use org.springframework.integration.acks.AcknowledgmentCallback. 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: RocketMQMessageChannelBinder.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Override
protected MessageHandler getPolledConsumerErrorMessageHandler(
		ConsumerDestination destination, String group,
		ExtendedConsumerProperties<RocketMQConsumerProperties> properties) {
	return message -> {
		if (message.getPayload() instanceof MessagingException) {
			AcknowledgmentCallback ack = StaticMessageHeaderAccessor
					.getAcknowledgmentCallback(
							((MessagingException) message.getPayload())
									.getFailedMessage());
			if (ack != null) {
				if (properties.getExtension().shouldRequeue()) {
					ack.acknowledge(Status.REQUEUE);
				}
				else {
					ack.acknowledge(Status.REJECT);
				}
			}
		}
	};
}
 
Example #2
Source File: PubSubMessageSourceTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void doReceive_manualAckModeAppliesAcknowledgmentHeaderAndDoesNotAck() {

	PubSubMessageSource pubSubMessageSource = new PubSubMessageSource(
			this.mockPubSubSubscriberOperations, "sub1");
	pubSubMessageSource.setMaxFetchSize(1);
	pubSubMessageSource.setPayloadType(String.class);
	pubSubMessageSource.setAckMode(AckMode.MANUAL);

	MessageBuilder<String> message = (MessageBuilder<String>) pubSubMessageSource.doReceive(1);

	assertThat(message).isNotNull();

	assertThat(message.getPayload()).isEqualTo("msg1");
	AcknowledgmentCallback callback = (AcknowledgmentCallback) message.getHeaders()
			.get(IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK);
	assertThat(callback).isNotNull();
	assertThat(callback.isAcknowledged()).isFalse();
	verify(this.msg1, times(0)).ack();

	callback.acknowledge(AcknowledgmentCallback.Status.ACCEPT);
	verify(this.msg1, times(1)).ack();
	assertThat(callback.isAcknowledged()).isTrue();
}
 
Example #3
Source File: PubSubAcknowledgmentCallback.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * In {@link AckMode#AUTO_ACK} mode, nacking cannot be done through this callback.
 * <p>Use {@link org.springframework.cloud.gcp.pubsub.support.GcpPubSubHeaders#ORIGINAL_MESSAGE}
 * to nack instead.
 */
@Override
public void acknowledge(Status status) {
	if (status == AcknowledgmentCallback.Status.ACCEPT) {
		this.message.ack();
	}
	else if (this.ackMode == AckMode.MANUAL || this.ackMode == AckMode.AUTO) {
		this.message.nack();
	}
	this.acknowledged = true;
}
 
Example #4
Source File: PubSubAcknowledgmentCallbackTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void acknowledge_acksOnAccept() {
	PubSubAcknowledgmentCallback callback = new PubSubAcknowledgmentCallback(this.mockMessage, AckMode.AUTO);
	callback.acknowledge(AcknowledgmentCallback.Status.ACCEPT);
	verify(this.mockMessage).ack();
	assertThat(callback.isAcknowledged()).isTrue();
}
 
Example #5
Source File: PubSubAcknowledgmentCallbackTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void acknowledge_nacksOnReject() {
	PubSubAcknowledgmentCallback callback = new PubSubAcknowledgmentCallback(this.mockMessage, AckMode.AUTO);
	callback.acknowledge(AcknowledgmentCallback.Status.REJECT);
	verify(this.mockMessage).nack();
	assertThat(callback.isAcknowledged()).isTrue();
}
 
Example #6
Source File: PubSubAcknowledgmentCallbackTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void acknowledge_nacksOnRequeue() {
	PubSubAcknowledgmentCallback callback = new PubSubAcknowledgmentCallback(this.mockMessage, AckMode.AUTO);
	callback.acknowledge(AcknowledgmentCallback.Status.REQUEUE);
	verify(this.mockMessage).nack();
	assertThat(callback.isAcknowledged()).isTrue();
}
 
Example #7
Source File: KafkaMessageChannelBinder.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Override
protected MessageHandler getPolledConsumerErrorMessageHandler(
		ConsumerDestination destination, String group,
		ExtendedConsumerProperties<KafkaConsumerProperties> properties) {
	if (properties.getExtension().isEnableDlq()) {
		return getErrorMessageHandler(destination, group, properties);
	}
	final MessageHandler superHandler = super.getErrorMessageHandler(destination,
			group, properties);
	return (message) -> {
		ConsumerRecord<?, ?> record = (ConsumerRecord<?, ?>) message.getHeaders()
				.get(KafkaHeaders.RAW_DATA);
		if (!(message instanceof ErrorMessage)) {
			logger.error("Expected an ErrorMessage, not a "
					+ message.getClass().toString() + " for: " + message);
		}
		else if (record == null) {
			if (superHandler != null) {
				superHandler.handleMessage(message);
			}
		}
		else {
			if (message.getPayload() instanceof MessagingException) {
				AcknowledgmentCallback ack = StaticMessageHeaderAccessor
						.getAcknowledgmentCallback(
								((MessagingException) message.getPayload())
										.getFailedMessage());
				if (ack != null) {
					if (isAutoCommitOnError(properties)) {
						ack.acknowledge(AcknowledgmentCallback.Status.REJECT);
					}
					else {
						ack.acknowledge(AcknowledgmentCallback.Status.REQUEUE);
					}
				}
			}
		}
	};
}
 
Example #8
Source File: RabbitMessageChannelBinder.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Override
protected MessageHandler getPolledConsumerErrorMessageHandler(
		ConsumerDestination destination, String group,
		ExtendedConsumerProperties<RabbitConsumerProperties> properties) {
	MessageHandler handler = getErrorMessageHandler(destination, group, properties);
	if (handler != null) {
		return handler;
	}
	final MessageHandler superHandler = super.getErrorMessageHandler(destination,
			group, properties);
	return message -> {
		Message amqpMessage = (Message) message.getHeaders()
				.get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE);
		if (!(message instanceof ErrorMessage)) {
			logger.error("Expected an ErrorMessage, not a "
					+ message.getClass().toString() + " for: " + message);
		}
		else if (amqpMessage == null) {
			if (superHandler != null) {
				superHandler.handleMessage(message);
			}
		}
		else {
			if (message.getPayload() instanceof MessagingException) {
				AcknowledgmentCallback ack = StaticMessageHeaderAccessor
						.getAcknowledgmentCallback(
								((MessagingException) message.getPayload())
										.getFailedMessage());
				if (ack != null) {
					if (properties.getExtension().isRequeueRejected()) {
						ack.acknowledge(Status.REQUEUE);
					}
					else {
						ack.acknowledge(Status.REJECT);
					}
				}
			}
		}
	};
}
 
Example #9
Source File: DefaultPollableMessageSource.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
private void requeueOrNack(Message<?> message, AcknowledgmentCallback ackCallback, MessagingException e) {
	if (!ackCallback.isAcknowledged() && shouldRequeue(e)) {
		AckUtils.requeue(ackCallback);
	}
	else {
		AckUtils.autoNack(ackCallback);
		if (e.getFailedMessage().equals(message)) {
			throw e;
		}
		throw new MessageHandlingException(message, e);
	}
}
 
Example #10
Source File: PollableConsumerTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequeue() {
	TestChannelBinder binder = createBinder();
	MessageConverterConfigurer configurer = this.context
			.getBean(MessageConverterConfigurer.class);

	DefaultPollableMessageSource pollableSource = new DefaultPollableMessageSource(
			this.messageConverter);
	configurer.configurePolledMessageSource(pollableSource, "foo");
	AcknowledgmentCallback callback = mock(AcknowledgmentCallback.class);
	pollableSource.addInterceptor(new ChannelInterceptor() {

		@Override
		public Message<?> preSend(Message<?> message, MessageChannel channel) {
			return MessageBuilder.fromMessage(message)
					.setHeader(
							IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK,
							callback)
					.build();
		}

	});
	ExtendedConsumerProperties<Object> properties = new ExtendedConsumerProperties<>(null);
	properties.setMaxAttempts(2);
	properties.setBackOffInitialInterval(0);
	binder.bindPollableConsumer("foo", "bar", pollableSource, properties);
	final AtomicInteger count = new AtomicInteger();
	try {
		assertThat(pollableSource.poll(received -> {
			count.incrementAndGet();
			throw new RequeueCurrentMessageException("test retry");
		})).isTrue();
	}
	catch (Exception e) {
		// no op
	}
	assertThat(count.get()).isEqualTo(2);
	verify(callback).acknowledge(Status.REQUEUE);
}
 
Example #11
Source File: PollableConsumerTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequeueFromErrorFlow() {
	TestChannelBinder binder = createBinder();
	MessageConverterConfigurer configurer = this.context
			.getBean(MessageConverterConfigurer.class);

	DefaultPollableMessageSource pollableSource = new DefaultPollableMessageSource(
			this.messageConverter);
	configurer.configurePolledMessageSource(pollableSource, "foo");
	AcknowledgmentCallback callback = mock(AcknowledgmentCallback.class);
	pollableSource.addInterceptor(new ChannelInterceptor() {

		@Override
		public Message<?> preSend(Message<?> message, MessageChannel channel) {
			return MessageBuilder.fromMessage(message)
					.setHeader(
							IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK,
							callback)
					.build();
		}

	});
	ExtendedConsumerProperties<Object> properties = new ExtendedConsumerProperties<>(null);
	properties.setMaxAttempts(1);
	binder.bindPollableConsumer("foo", "bar", pollableSource, properties);
	SubscribableChannel errorChannel = new DirectChannel();
	errorChannel.subscribe(msg -> {
		throw new RequeueCurrentMessageException((Throwable) msg.getPayload());
	});
	pollableSource.setErrorChannel(errorChannel);
	try {
		pollableSource.poll(received -> {
			throw new RuntimeException("test requeue from error flow");
		});
	}
	catch (Exception e) {
		// no op
	}
	verify(callback).acknowledge(Status.REQUEUE);
}
 
Example #12
Source File: RocketMQMessageSource.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Override
protected synchronized Object doReceive() {
	if (messageQueueChooser.getMessageQueues() == null
			|| messageQueueChooser.getMessageQueues().size() == 0) {
		return null;
	}
	try {
		int count = 0;
		while (count < messageQueueChooser.getMessageQueues().size()) {
			MessageQueue messageQueue;
			synchronized (this.consumerMonitor) {
				messageQueue = messageQueueChooser.choose();
				messageQueueChooser.increment();
			}

			long offset = consumer.fetchConsumeOffset(messageQueue,
					rocketMQConsumerProperties.getExtension().isFromStore());

			log.debug("topic='{}', group='{}', messageQueue='{}', offset now='{}'",
					this.topic, this.group, messageQueue, offset);

			PullResult pullResult;
			if (messageSelector != null) {
				pullResult = consumer.pull(messageQueue, messageSelector, offset, 1);
			}
			else {
				pullResult = consumer.pull(messageQueue, (String) null, offset, 1);
			}

			if (pullResult.getPullStatus() == PullStatus.FOUND) {
				List<MessageExt> messageExtList = pullResult.getMsgFoundList();

				Message message = RocketMQUtil
						.convertToSpringMessage(messageExtList.get(0));

				AcknowledgmentCallback ackCallback = this.ackCallbackFactory
						.createCallback(new RocketMQAckInfo(messageQueue, pullResult,
								consumer, offset));

				Message messageResult = MessageBuilder.fromMessage(message).setHeader(
						IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK,
						ackCallback).build();
				return messageResult;
			}
			else {
				log.debug("messageQueue='{}' PullResult='{}' with topic `{}`",
						messageQueueChooser.getMessageQueues(),
						pullResult.getPullStatus(), topic);
			}
			count++;
		}
	}
	catch (Exception e) {
		log.error("Consumer pull error: " + e.getMessage(), e);
	}
	return null;
}
 
Example #13
Source File: RocketMQMessageSource.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Override
public AcknowledgmentCallback createCallback(RocketMQAckInfo info) {
	return new RocketMQAckCallback(info);
}
 
Example #14
Source File: PubSubAcknowledgmentCallbackTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void isAcknowledgedTrueAfterAccept() {
	PubSubAcknowledgmentCallback callback = new PubSubAcknowledgmentCallback(this.mockMessage, AckMode.MANUAL);
	callback.acknowledge(AcknowledgmentCallback.Status.ACCEPT);
	assertThat(callback.isAcknowledged()).isTrue();
}
 
Example #15
Source File: PubSubAcknowledgmentCallbackTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void isAcknowledgedTrueAfterReject() {
	PubSubAcknowledgmentCallback callback = new PubSubAcknowledgmentCallback(this.mockMessage, AckMode.MANUAL);
	callback.acknowledge(AcknowledgmentCallback.Status.REJECT);
	assertThat(callback.isAcknowledged()).isTrue();
}