de.otto.synapse.consumer.MessageConsumer Maven / Gradle / Ivy
Show all versions of synapse-core Show documentation
package de.otto.synapse.consumer;
import de.otto.synapse.configuration.SynapseProperties;
import de.otto.synapse.eventsource.EventSource;
import de.otto.synapse.eventsource.EventSourceConsumerProcess;
import de.otto.synapse.message.Message;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.ThreadSafe;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.compile;
/**
* A consumer endpoint for {@link Message messages} with payload-type <T>.
*
*
*
*
* Multiple EventConsumers may listen at a single {@link EventSource}. A single EventConsumer
* must be registered to multiple EventSources.
*
*
* By default, Synapse is auto-configuring a {@link EventSourceConsumerProcess} that is
* running a separate thread for every MessageConsumer. The thread is taking care for continuous
* consumption of messages using the consumers, until the application is shutting down.
*
*
* If you need to manually consume messages using MessageConsumers, auto-configuration of the
* {@code EventSourceConsumerProcess} can be disabled by setting
* {@link SynapseProperties.ConsumerProcess#setEnabled(boolean) synapse.consumer-process.enabled=false}
*
*
* MessageConsumers are expected to be thread-safe.
*
*
* @param the type of the messages's payload
*/
@ThreadSafe
public interface MessageConsumer extends Consumer> {
static MessageConsumer of(final String keyPattern,
final Class payloadType,
final Consumer> consumer) {
return new MessageConsumer() {
private Pattern pattern = compile(keyPattern);
@Override
@Nonnull
public Class payloadType() {
return payloadType;
}
@Override
@Nonnull
public Pattern keyPattern() {
return pattern;
}
@Override
public void accept(Message tMessage) {
consumer.accept(tMessage);
}
};
}
/**
* Returns the expected payload type of {@link Message events} consumed by this EventConsumer.
*
* @return payload type
*/
@Nonnull
Class payloadType();
/**
* Returns the pattern of {@link de.otto.synapse.message.Message#getKey() message keys} accepted by this consumer.
*
* @return Pattern
*/
@Nonnull
Pattern keyPattern();
}