Skip to content

Add Reactive mode for AbstractPollingEndpoint #2429

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@

package org.springframework.integration.endpoint;

import java.time.Duration;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

import org.aopalliance.aop.Advice;
import org.reactivestreams.Subscription;

import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.BeanClassLoaderAware;
Expand All @@ -43,6 +46,7 @@
import org.springframework.messaging.MessagingException;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
Expand All @@ -51,6 +55,10 @@
import org.springframework.util.CollectionUtils;
import org.springframework.util.ErrorHandler;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

/**
* @author Mark Fisher
* @author Oleg Zhurakousky
Expand All @@ -66,23 +74,27 @@ public abstract class AbstractPollingEndpoint extends AbstractEndpoint implement

private boolean syncExecutor = true;

private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

private Trigger trigger = new PeriodicTrigger(10);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Default 10ms? Really?

If we must have a default, it should be much larger than this.

Why wouldn't we just say it's invalid to configure a reactive poller without a trigger?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh? This is an existing code. I just reformatted it a bit to remove some volatile.
We can reconsider the default in other issue, although I think Mark did this way to make as close to the event-driven behavior as possible

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doh; merging.


private long maxMessagesPerPoll = -1;

private ErrorHandler errorHandler;

private boolean errorHandlerIsDefault;

private Trigger trigger = new PeriodicTrigger(10);

private List<Advice> adviceChain;

private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
private TransactionSynchronizationFactory transactionSynchronizationFactory;

private long maxMessagesPerPoll = -1;
private volatile Callable<Message<?>> pollingTask;

private TransactionSynchronizationFactory transactionSynchronizationFactory;
private volatile Flux<Message<?>> pollingFlux;

private volatile ScheduledFuture<?> runningTask;
private volatile Subscription subscription;

private volatile Runnable poller;
private volatile ScheduledFuture<?> runningTask;

private volatile boolean initialized;

Expand Down Expand Up @@ -167,6 +179,14 @@ protected boolean isReceiveOnlyAdvice(Advice advice) {
protected void applyReceiveOnlyAdviceChain(Collection<Advice> chain) {
}

protected boolean isReactive() {
return false;
}

protected Flux<Message<?>> getPollingFlux() {
return this.pollingFlux;
}

@Override
protected void onInit() {
synchronized (this.initializationMonitor) {
Expand Down Expand Up @@ -200,16 +220,38 @@ protected void onInit() {
}
}

// LifecycleSupport implementation

@Override // guarded by super#lifecycleLock
protected void doStart() {
if (!this.initialized) {
onInit();
}

this.pollingTask = createPollingTask();

if (isReactive()) {
this.pollingFlux = createFluxGenerator();
}
else {
Assert.state(getTaskScheduler() != null, "unable to start polling, no taskScheduler available");

this.runningTask =
getTaskScheduler()
.schedule(createPoller(), this.trigger);
}
}

@SuppressWarnings("unchecked")
private Runnable createPoller() throws Exception {
private Callable<Message<?>> createPollingTask() {
List<Advice> receiveOnlyAdviceChain = null;
if (!CollectionUtils.isEmpty(this.adviceChain)) {
receiveOnlyAdviceChain = this.adviceChain.stream()
.filter(this::isReceiveOnlyAdvice)
.collect(Collectors.toList());
}

Callable<Boolean> pollingTask = this::doPoll;
Callable<Message<?>> pollingTask = this::doPoll;

List<Advice> adviceChain = this.adviceChain;
if (!CollectionUtils.isEmpty(adviceChain)) {
Expand All @@ -219,65 +261,122 @@ private Runnable createPoller() throws Exception {
.filter(advice -> !isReceiveOnlyAdvice(advice))
.forEach(proxyFactory::addAdvice);
}
pollingTask = (Callable<Boolean>) proxyFactory.getProxy(this.beanClassLoader);
pollingTask = (Callable<Message<?>>) proxyFactory.getProxy(this.beanClassLoader);
}
if (!CollectionUtils.isEmpty(receiveOnlyAdviceChain)) {
applyReceiveOnlyAdviceChain(receiveOnlyAdviceChain);
}
return new Poller(pollingTask);

return pollingTask;
}

// LifecycleSupport implementation
private Runnable createPoller() {
return () ->
this.taskExecutor.execute(() -> {
int count = 0;
while (this.initialized && (this.maxMessagesPerPoll <= 0 || count < this.maxMessagesPerPoll)) {
if (pollForMessage() == null) {
break;
}
count++;
}
});
}

@Override // guarded by super#lifecycleLock
protected void doStart() {
if (!this.initialized) {
this.onInit();
}
Assert.state(this.getTaskScheduler() != null,
"unable to start polling, no taskScheduler available");
private Flux<Message<?>> createFluxGenerator() {
SimpleTriggerContext triggerContext = new SimpleTriggerContext();

return Flux
.<Duration>generate(sink -> {
Date date = this.trigger.nextExecutionTime(triggerContext);
if (date != null) {
triggerContext.update(date, null, null);
long millis = date.getTime() - System.currentTimeMillis();
sink.next(Duration.ofMillis(millis));
}
else {
sink.complete();
}
})
.concatMap(duration ->
Mono.delay(duration)
.doOnNext(l ->
triggerContext.update(triggerContext.lastScheduledExecutionTime(),
new Date(), null))
.flatMapMany(l ->
Flux
.<Message<?>>generate(fluxSink -> {
Message<?> message = pollForMessage();
if (message != null) {
fluxSink.next(message);
}
else {
fluxSink.complete();
}
})
.take(this.maxMessagesPerPoll)
.subscribeOn(Schedulers.fromExecutor(this.taskExecutor))
.doOnComplete(() ->
triggerContext.update(triggerContext.lastScheduledExecutionTime(),
triggerContext.lastActualExecutionTime(),
new Date())
)), 1)
.repeat(this::isRunning)
.doOnSubscribe(subscription -> this.subscription = subscription);
}

private Message<?> pollForMessage() {
try {
this.poller = createPoller();
return this.pollingTask.call();
}
catch (Exception e) {
this.initialized = false;
throw new MessagingException("Failed to create Poller", e);
if (e instanceof MessagingException) {
throw (MessagingException) e;
}
else {
Message<?> failedMessage = null;
if (this.transactionSynchronizationFactory != null) {
Object resource = TransactionSynchronizationManager.getResource(getResourceToBind());
if (resource instanceof IntegrationResourceHolder) {
failedMessage = ((IntegrationResourceHolder) resource).getMessage();
}
}
throw new MessagingException(failedMessage, e);
}
}
this.runningTask = this.getTaskScheduler().schedule(this.poller, this.trigger);
}

@Override // guarded by super#lifecycleLock
protected void doStop() {
if (this.runningTask != null) {
this.runningTask.cancel(true);
finally {
if (this.transactionSynchronizationFactory != null) {
Object resource = getResourceToBind();
if (TransactionSynchronizationManager.hasResource(resource)) {
TransactionSynchronizationManager.unbindResource(resource);
}
}
}
this.runningTask = null;
}

private boolean doPoll() {
IntegrationResourceHolder holder = this.bindResourceHolderIfNecessary(
this.getResourceKey(), this.getResourceToBind());
Message<?> message = null;
private Message<?> doPoll() {
IntegrationResourceHolder holder = bindResourceHolderIfNecessary(getResourceKey(), getResourceToBind());
Message<?> message;
try {
message = this.receiveMessage();
message = receiveMessage();
}
catch (Exception e) {
if (Thread.interrupted()) {
if (logger.isDebugEnabled()) {
logger.debug("Poll interrupted - during stop()? : " + e.getMessage());
}
return false;
return null;
}
else {
throw (RuntimeException) e;
}
}
boolean result;

if (message == null) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Received no Message during the poll, returning 'false'");
}
result = false;
return null;
}
else {
if (this.logger.isDebugEnabled()) {
Expand All @@ -286,20 +385,35 @@ private boolean doPoll() {
if (holder != null) {
holder.setMessage(message);
}
try {
this.handleMessage(message);
}
catch (Exception e) {
if (e instanceof MessagingException) {
throw new MessagingExceptionWrapper(message, (MessagingException) e);

if (!isReactive()) {
try {
handleMessage(message);
}
else {
throw new MessagingException(message, e);
catch (Exception e) {
if (e instanceof MessagingException) {
throw new MessagingExceptionWrapper(message, (MessagingException) e);
}
else {
throw new MessagingException(message, e);
}
}
}
result = true;
}
return result;

return message;
}

@Override // guarded by super#lifecycleLock
protected void doStop() {
if (this.runningTask != null) {
this.runningTask.cancel(true);
}
this.runningTask = null;

if (this.subscription != null) {
this.subscription.cancel();
}
}

/**
Expand Down Expand Up @@ -369,57 +483,4 @@ private IntegrationResourceHolder bindResourceHolderIfNecessary(String key, Obje
return null;
}

/**
* Default Poller implementation
*/
private final class Poller implements Runnable {

private final Callable<Boolean> pollingTask;

Poller(Callable<Boolean> pollingTask) {
this.pollingTask = pollingTask;
}

@Override
public void run() {
AbstractPollingEndpoint.this.taskExecutor.execute(() -> {
int count = 0;
while (AbstractPollingEndpoint.this.initialized
&& (AbstractPollingEndpoint.this.maxMessagesPerPoll <= 0
|| count < AbstractPollingEndpoint.this.maxMessagesPerPoll)) {
try {
if (!Poller.this.pollingTask.call()) {
break;
}
count++;
}
catch (Exception e) {
if (e instanceof MessagingException) {
throw (MessagingException) e;
}
else {
Message<?> failedMessage = null;
if (AbstractPollingEndpoint.this.transactionSynchronizationFactory != null) {
Object resource = TransactionSynchronizationManager.getResource(getResourceToBind());
if (resource instanceof IntegrationResourceHolder) {
failedMessage = ((IntegrationResourceHolder) resource).getMessage();
}
}
throw new MessagingException(failedMessage, e);
}
}
finally {
if (AbstractPollingEndpoint.this.transactionSynchronizationFactory != null) {
Object resource = getResourceToBind();
if (TransactionSynchronizationManager.hasResource(resource)) {
TransactionSynchronizationManager.unbindResource(resource);
}
}
}
}
});
}

}

}
Loading