Spring Integration: channels, flows and gateways
Spring Integration implements the Enterprise Integration Patterns inside a Spring application: messages travel through channels between small endpoints that filter, route, transform and combine them. This page explains the model, then runs complete Spring Boot 4.1 programs for channels, the Java DSL, gateways, splitting and aggregating, error handling and polling.
Contents
Messages, channels and endpoints
Spring Integration is Spring's implementation of the Enterprise Integration Patterns, the catalogue of messaging patterns described by Gregor Hohpe and Bobby Woolf. Instead of one service method calling the next, the steps of a process exchange messages, and each step only knows the channel it reads from and the channel it writes to. That makes it easy to add a step, run a step on another thread, or replace an in-memory channel with a file, a queue or an HTTP call.
Three building blocks make up every integration:
- Message: an immutable payload plus headers, the
type shared with Spring's other messaging modules. Headers carry ids, correlation data, reply addresses and your own values.org.springframework.messaging.Message - Channel: the pipe between steps. Its type decides whether the next step runs on the sender's thread, on another thread, or later, when someone polls.
- Endpoint: a step that consumes from a channel. The common ones are filter, transformer, router, splitter, aggregator and service activator (a plain handler method), plus gateways and channel adapters at the edges.
| DSL method | Pattern | What it does |
|---|---|---|
filter | Message filter | Passes or drops a message, optionally to a discard flow |
transform | Message translator | Changes the payload |
enrichHeaders | Content enricher | Adds headers |
route | Content-based router | Sends each message to one of several channels or sub-flows |
splitaggregate | Splitter, aggregator | Breaks a message into parts and joins the results back |
handle | Service activator | Calls your code, optionally producing a reply |
wireTap | Wire tap | Copies messages to a side flow, for auditing or debugging |
IntegrationFlow.from(Interface.class) | Messaging gateway | Lets plain Java code send messages and wait for replies |
The examples are Spring Boot 4.1 applications using spring-boot-starter-integrationerrorChanneltaskSchedulerspring-integration-file
Channel types and the threads they use
The channel type is the most important design decision in a flow, because it decides threading, buffering and how errors travel. Channels are plain objects, so this program creates each type directly and sends to it; the Spring Boot context only sets up logging:
package demo.integration.channels;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.ExecutorChannel;
import org.springframework.integration.channel.PublishSubscribeChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.support.MessageBuilder;
@SpringBootApplication
public class ChannelTypes {
static String thread() {
return Thread.currentThread().getName().replaceAll("-\\d+$", "-N");
}
static MessageHandler printer(String name) {
return message -> System.out.println(" " + name + " got '" + message.getPayload()
+ "' on " + thread());
}
public static void main(String[] args) throws Exception {
// the context is only used for its logging setup; the channels are plain objects
SpringApplication app = new SpringApplication(ChannelTypes.class);
app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
app.run(args).close();
System.out.println("1. DirectChannel: one subscriber per message, on the sender's thread");
DirectChannel direct = new DirectChannel();
direct.subscribe(printer("A"));
direct.subscribe(printer("B"));
for (int i = 1; i <= 3; i++) {
direct.send(MessageBuilder.withPayload("order " + i).build());
}
System.out.println("2. DirectChannel: a failing subscriber fails the send() call");
DirectChannel failing = new DirectChannel();
failing.subscribe(message -> {
throw new IllegalStateException("database down");
});
try {
failing.send(MessageBuilder.withPayload("order 4").build());
} catch (RuntimeException e) {
System.out.println(" send() threw " + e.getClass().getSimpleName()
+ ", cause: " + e.getCause().getMessage());
}
System.out.println("3. DirectChannel with no subscriber:");
try {
new DirectChannel().send(MessageBuilder.withPayload("lost").build());
} catch (MessageDeliveryException e) {
System.out.println(" " + e.getClass().getSimpleName());
}
System.out.println("4. PublishSubscribeChannel: every subscriber gets every message");
PublishSubscribeChannel pubSub = new PublishSubscribeChannel();
pubSub.subscribe(printer("email"));
pubSub.subscribe(printer("audit"));
pubSub.send(MessageBuilder.withPayload("order 5").build());
System.out.println("5. QueueChannel: messages wait until a consumer polls");
QueueChannel queue = new QueueChannel(2);
System.out.println(" send 1: " + queue.send(MessageBuilder.withPayload("a").build(), 0));
System.out.println(" send 2: " + queue.send(MessageBuilder.withPayload("b").build(), 0));
System.out.println(" send 3 to a full queue: "
+ queue.send(MessageBuilder.withPayload("c").build(), 0));
Message<?> first = queue.receive(100);
System.out.println(" received '" + first.getPayload() + "', queue size now "
+ queue.getQueueSize());
System.out.println("6. ExecutorChannel: the subscriber runs on a pool thread");
CountDownLatch done = new CountDownLatch(1);
AtomicReference<String> handledOn = new AtomicReference<>();
try (var pool = Executors.newSingleThreadExecutor(r -> new Thread(r, "worker-1"))) {
ExecutorChannel async = new ExecutorChannel(pool);
async.subscribe(message -> {
handledOn.set(thread());
done.countDown();
});
boolean sent = async.send(MessageBuilder.withPayload("order 6").build());
System.out.println(" send() returned " + sent + " on " + thread());
done.await(5, TimeUnit.SECONDS);
System.out.println(" the handler ran on " + handledOn.get());
}
}
}
1. DirectChannel: one subscriber per message, on the sender's thread
A got 'order 1' on main
B got 'order 2' on main
A got 'order 3' on main
2. DirectChannel: a failing subscriber fails the send() call
send() threw MessageDeliveryException, cause: database down
3. DirectChannel with no subscriber:
MessageDeliveryException
4. PublishSubscribeChannel: every subscriber gets every message
email got 'order 5' on main
audit got 'order 5' on main
5. QueueChannel: messages wait until a consumer polls
send 1: true
send 2: true
send 3 to a full queue: false
received 'a', queue size now 1
6. ExecutorChannel: the subscriber runs on a pool thread
send() returned true on main
the handler ran on worker-N
- The
with two subscribers delivered each message to one of them, in turn: A, B, A. Both ran onDirectChannel , the sender's thread, somain returned only after the handler had finished.send() - When the only subscriber threw,
threw asend() whose cause is the handler's exception. With a direct channel, the sender sees failures at once, and a surrounding transaction covers the handler too.MessageDeliveryException - A
with no subscriber cannot deliver at all, so the send failed. In a real flow this usually means a missing or misspelled channel name.DirectChannel - The
gave the same message to bothPublishSubscribeChannel andemail .audit - The
with capacity 2 accepted two messages and refused the third:QueueChannel returnedsend(message, 0) instead of waiting. A consumer tookfalse witha , leaving one message.receive - The
returnedExecutorChannel straight away and the handler ran ontrue , so the sender can no longer see the handler's result or its exceptions. The program records the handler's thread and prints it after waiting, because the two threads would otherwise print in no fixed order.worker-1
A DirectChannelsetFailover(false)
A flow with the Java DSL and a gateway
Real flows are declared as IntegrationFlow
package demo.integration.flow;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.Header;
@SpringBootApplication
public class OrderFlow {
record Order(String id, String country, int totalCents) { }
// The application only sees this interface; Spring Integration implements it
interface OrderGateway {
String place(Order order, @Header("source") String source);
}
@Bean
IntegrationFlow orders() {
return IntegrationFlow.from(OrderGateway.class)
// a wire tap copies each message to a side flow, here for auditing
.wireTap(tap -> tap.handle(m -> System.out.println(" [audit] "
+ m.getPayload() + " from " + m.getHeaders().get("source"))))
.<Order>filter(o -> o.totalCents() > 0, f -> f.discardFlow(
d -> d.handle((p, h) -> "rejected " + ((Order) p).id() + ": empty")))
.enrichHeaders(h -> h.headerFunction("vatPercent",
m -> ((Order) m.getPayload()).country().equals("DE") ? 19 : 20))
.<Order, String>route(Order::country, r -> r
.subFlowMapping("DE", sf -> sf.handle(OrderFlow::shipFromBerlin))
.defaultSubFlowMapping(sf -> sf.handle(OrderFlow::shipFromLyon)))
.get();
}
static String shipFromBerlin(Order order, MessageHeaders headers) {
return "Berlin ships " + order.id() + ", VAT " + headers.get("vatPercent") + "%";
}
static String shipFromLyon(Order order, MessageHeaders headers) {
return "Lyon ships " + order.id() + ", VAT " + headers.get("vatPercent") + "%";
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(OrderFlow.class);
app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
try (var context = app.run(args)) {
OrderGateway gateway = context.getBean(OrderGateway.class);
System.out.println("gateway is a proxy: "
+ gateway.getClass().getSimpleName().startsWith("$Proxy"));
System.out.println(gateway.place(new Order("o-1", "DE", 4999), "web"));
System.out.println(gateway.place(new Order("o-2", "FR", 1200), "mobile"));
System.out.println(gateway.place(new Order("o-3", "FR", 0), "web"));
}
}
}
gateway is a proxy: true
[audit] Order[id=o-1, country=DE, totalCents=4999] from web
Berlin ships o-1, VAT 19%
[audit] Order[id=o-2, country=FR, totalCents=1200] from mobile
Lyon ships o-2, VAT 20%
[audit] Order[id=o-3, country=FR, totalCents=0] from web
rejected o-3: empty
is a plain interface.OrderGateway made Spring create a JDK proxy for it and register it as a bean, so calling code never touches the messaging API.IntegrationFlow.from(OrderGateway.class)- The
parameter became a message header, which the wire tap printed: web, then mobile.@Header("source") - The wire tap's audit line came before each result, because the tap's side flow ran on the same thread before the main flow continued.
- o-1 is German, so the router sent it to the
sub-flow, which read theDE header of 19. o-2 went to the default sub-flow with 20%.vatPercent - o-3 has a total of 0, so the filter discarded it. The discard flow produced a reply, and the gateway returned it as
.rejected o-3: empty
The gateway method returns a Stringvoid
Annotating the interface with @MessagingGateway
Splitting work and aggregating the results
A splitter breaks one message into several, and an aggregator collects the results back into one, which is the usual way to process the parts of a request in parallel. Each cart line here is priced on a pool thread. The simulated pricing calls take 300 ms for pens, 100 ms for books and 200 ms for mugs, so the lines finish in a different order from the cart:
package demo.integration.split;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.IntegrationMessageHeaderAccessor;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.MessageChannels;
import org.springframework.messaging.Message;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@SpringBootApplication
public class SplitAggregate {
record Line(String sku, int quantity) { }
record Cart(String id, List<Line> lines) { }
record Priced(String sku, int sequence, int cents) { }
interface Checkout {
String total(Cart cart);
}
// price per item, and how long the (simulated) pricing service takes for it
static final Map<String, Integer> PRICES = Map.of("pen", 150, "book", 1299, "mug", 800);
static final Map<String, Integer> DELAYS = Map.of("pen", 300, "book", 100, "mug", 200);
@Bean
ThreadPoolTaskExecutor pricingPool() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(3);
pool.setThreadNamePrefix("pricing-");
return pool;
}
@Bean
IntegrationFlow checkout(ThreadPoolTaskExecutor pricingPool) {
return IntegrationFlow.from(Checkout.class)
.split(Cart.class, Cart::lines)
// each line is priced on its own thread, in parallel
.channel(MessageChannels.executor(pricingPool))
.handle(Line.class, (line, headers) -> {
sleep(DELAYS.get(line.sku()));
int sequence = (Integer) headers.get(
IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER);
return new Priced(line.sku(), sequence,
PRICES.get(line.sku()) * line.quantity());
})
.aggregate(a -> a.outputProcessor(group -> {
int total = 0;
StringBuilder arrival = new StringBuilder();
for (Message<?> m : group.getMessages()) {
Priced p = (Priced) m.getPayload();
total += p.cents();
arrival.append(p.sku()).append("(line ").append(p.sequence())
.append(") ");
}
return "arrived " + arrival + "-> " + group.size() + " lines, total "
+ total / 100.0 + " EUR";
}))
.get();
}
static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(SplitAggregate.class);
app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
try (var context = app.run(args)) {
Checkout checkout = context.getBean(Checkout.class);
Cart cart = new Cart("c-1", List.of(new Line("pen", 4), new Line("book", 1),
new Line("mug", 2)));
long start = System.nanoTime();
System.out.println("cart c-1: " + checkout.total(cart));
System.out.println("took about " + Math.round((System.nanoTime() - start)
/ 1000000 / 100.0) * 100 + " ms for 300 + 100 + 200 ms of pricing");
}
}
}
cart c-1: arrived book(line 2) mug(line 3) pen(line 1) -> 3 lines, total 34.99 EUR
took about 300 ms for 300 + 100 + 200 ms of pricing
- The splitter turned the cart into three messages and gave each one
,sequenceNumber andsequenceSize headers.correlationId - The executor channel priced the three lines in parallel on the
pool. They arrived at the aggregator in finishing order: book (line 2), mug (line 3), then pen (line 1).pricing- - The aggregator grouped them by correlation id and released the group when all three of the
parts were in. The total, 4 x 1.50 + 12.99 + 2 x 8.00, is 34.99 EUR.sequenceSize - The whole checkout took about as long as the slowest line, not the 600 ms sum.
The aggregator keeps incomplete groups in a message store, in memory by default. If one part never arrives, the group waits forever unless you set groupTimeoutJdbcMessageStoreExecutors
Errors: thrown, replied or sent to errorChannel
Where an exception goes depends on the thread it happens on. This program has a payment flow that declines one card number, a variant whose gateway has an error channel, and a notification flow that fails on another thread:
package demo.integration.errors;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.MessageChannels;
import org.springframework.messaging.MessagingException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@SpringBootApplication
public class ErrorChannels {
static final CountDownLatch ASYNC_ERROR = new CountDownLatch(1);
interface Payments {
String charge(String card);
}
interface SafePayments {
String charge(String card);
}
@MessagingGateway(defaultRequestChannel = "notifications.input")
interface Notifier {
void notify(String text);
}
static String charge(String card) {
if (card.startsWith("0000")) {
throw new IllegalArgumentException("card " + card + " declined");
}
return "charged " + card;
}
@Bean
IntegrationFlow payments() {
return IntegrationFlow.from(Payments.class)
.<String, String>transform(ErrorChannels::charge)
.get();
}
@Bean
IntegrationFlow safePayments() {
return IntegrationFlow.from(SafePayments.class, g -> g.errorChannel("paymentErrors"))
.<String, String>transform(ErrorChannels::charge)
.get();
}
// the gateway's error channel: its reply goes back to the caller instead of the error
@Bean
IntegrationFlow paymentErrorFlow() {
return IntegrationFlow.from("paymentErrors")
.<MessagingException, String>transform(e -> "fallback: "
+ e.getCause().getMessage() + ", queued for manual review")
.get();
}
@Bean
ThreadPoolTaskExecutor mailPool() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setThreadNamePrefix("mail-");
return pool;
}
// fire and forget, handled on another thread: nobody waits for the outcome
@Bean
IntegrationFlow notifications(ThreadPoolTaskExecutor mailPool) {
return f -> f.channel(MessageChannels.executor(mailPool))
.handle(m -> {
throw new IllegalStateException("SMTP server unreachable");
});
}
// the global errorChannel receives failures from asynchronous flows
@Bean
IntegrationFlow globalErrors() {
return IntegrationFlow.from("errorChannel")
.handle(m -> {
MessagingException e = (MessagingException) m.getPayload();
System.out.println(" [errorChannel] " + e.getClass().getSimpleName()
+ ": " + e.getCause().getMessage() + ", failed payload '"
+ e.getFailedMessage().getPayload() + "'");
ASYNC_ERROR.countDown();
})
.get();
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(ErrorChannels.class);
app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
"logging.level.root", "OFF"));
try (var context = app.run(args)) {
Payments payments = context.getBean(Payments.class);
System.out.println("1. Synchronous flow: the exception reaches the caller");
System.out.println(" " + payments.charge("4111-1111"));
try {
payments.charge("0000-0000");
} catch (RuntimeException e) {
System.out.println(" caught " + e.getClass().getSimpleName() + ": "
+ e.getMessage());
}
System.out.println("2. Gateway with an errorChannel: the caller gets a reply");
System.out.println(" " + context.getBean(SafePayments.class).charge("0000-0000"));
System.out.println("3. Asynchronous flow: the caller cannot see the error");
context.getBean(Notifier.class).notify("your order shipped");
System.out.println(" notify() returned normally");
ASYNC_ERROR.await(5, TimeUnit.SECONDS);
}
}
}
1. Synchronous flow: the exception reaches the caller
charged 4111-1111
caught IllegalArgumentException: card 0000-0000 declined
2. Gateway with an errorChannel: the caller gets a reply
fallback: card 0000-0000 declined, queued for manual review
3. Asynchronous flow: the caller cannot see the error
notify() returned normally
[errorChannel] MessageDeliveryException: SMTP server unreachable, failed payload 'your order shipped'
- The payment flow ran on the caller's thread, so the exception came back through the gateway. The gateway unwrapped Spring Integration's
and rethrew the originalMessageHandlingException , so the caller can catch its own exception type.IllegalArgumentException - The second gateway was given
. The failure was sent there as anerrorChannel("paymentErrors") , and the reply of the error flow became the gateway's return value: a fallback instead of an exception.ErrorMessage - The notification gateway returns
and the flow handed the message to thevoid pool, somail- returned normally. The exception then went to the globalnotify() , wrapped in aerrorChannel that still holds the failed message.MessageDeliveryException
By default, the global errorChannelglobalErrors
Polling a source
Many sources cannot push messages: a database table, a directory, a mailbox. A polling channel adapter checks them on a schedule and turns each new item into a message. Here a queue of five invoices stands in for such a source, polled every 200 ms with at most two items per poll:
package demo.integration.polling;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.Pollers;
@SpringBootApplication
public class PollingSource {
// stands in for a table, a directory or a mailbox that is checked periodically
static final Queue<String> INBOX = new ArrayDeque<>(List.of("invoice-1", "invoice-2",
"invoice-3", "invoice-4", "invoice-5"));
static final CountDownLatch DONE = new CountDownLatch(5);
static volatile long first;
static synchronized String nextOrNull() {
return INBOX.poll(); // null means "nothing new": no message is created
}
@Bean
IntegrationFlow invoices() {
return IntegrationFlow.fromSupplier(PollingSource::nextOrNull,
e -> e.poller(Pollers.fixedDelay(Duration.ofMillis(200))
.maxMessagesPerPoll(2)))
.<String, String>transform(String::toUpperCase)
.handle(m -> {
long now = System.nanoTime();
if (first == 0) {
first = now;
}
long ms = Math.round((now - first) / 1000000 / 100.0) * 100;
System.out.println(" at about " + ms + " ms: " + m.getPayload()
+ " on " + Thread.currentThread().getName()
.replaceAll("-\\d+$", "-N"));
DONE.countDown();
})
.get();
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(PollingSource.class);
app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
var context = app.run(args);
System.out.println("all 5 handled: " + DONE.await(10, TimeUnit.SECONDS));
context.close();
}
}
at about 0 ms: INVOICE-1 on scheduling-N
at about 0 ms: INVOICE-2 on scheduling-N
at about 200 ms: INVOICE-3 on scheduling-N
at about 200 ms: INVOICE-4 on scheduling-N
at about 400 ms: INVOICE-5 on scheduling-N
all 5 handled: true
- The first poll took two invoices, the next poll, about 200 ms later, two more, and the third poll the last one.
limited each poll.maxMessagesPerPoll(2) - When the supplier returned
, no message was created, so later polls did nothing.null - The polls ran on
, a thread of thescheduling-N that Spring Boot auto-configures, and the rest of the flow ran on that thread too.TaskScheduler
fixedDelayfixedRatecronspring.integration.poller.*
Channel adapters for external systems
Adapters connect a flow to the outside world. Each lives in its own module, and in the Java DSL each module has a factory class: FilesHttpJmsKafkaJdbcMailinboxprocessedspring-integration-fileFilesjava.nio.file.Files
package demo.integration.files;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.Pollers;
import org.springframework.integration.file.FileHeaders;
import org.springframework.integration.file.dsl.FileWritingMessageHandlerSpec;
import org.springframework.integration.file.support.FileExistsMode;
@SpringBootApplication
public class FileFlow {
static Path inbox;
static Path processed;
static final LinkedBlockingQueue<String> WRITTEN = new LinkedBlockingQueue<>();
@Bean
IntegrationFlow csvImport() {
FileWritingMessageHandlerSpec writer =
org.springframework.integration.file.dsl.Files // clashes with nio Files
.outboundGateway(processed.toFile())
.fileExistsMode(FileExistsMode.REPLACE);
return IntegrationFlow
.from(org.springframework.integration.file.dsl.Files // same clash
.inboundAdapter(inbox.toFile(),
Comparator.comparing(File::getName))
.patternFilter("*.csv"),
e -> e.poller(Pollers.fixedDelay(Duration.ofMillis(100))))
.enrichHeaders(h -> h.headerExpression("source",
"headers['" + FileHeaders.FILENAME + "']"))
.transform(org.springframework.integration.file.dsl.Files.toStringTransformer())
.<String, String>transform(String::toUpperCase)
.handle(writer)
.handle(m -> WRITTEN.add(m.getHeaders().get("source") + " -> processed/"
+ ((File) m.getPayload()).getName()))
.get();
}
static void show(String label) throws InterruptedException {
System.out.println(label);
String line;
while ((line = WRITTEN.poll(600, TimeUnit.MILLISECONDS)) != null) {
System.out.println(" " + line);
}
}
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("si-files");
inbox = Files.createDirectory(root.resolve("inbox"));
processed = Files.createDirectory(root.resolve("processed"));
Files.writeString(inbox.resolve("orders.csv"), "id,sku\n1,book\n");
Files.writeString(inbox.resolve("customers.csv"), "id,name\n7,ann\n");
Files.writeString(inbox.resolve("readme.txt"), "not a csv\n");
SpringApplication app = new SpringApplication(FileFlow.class);
app.setDefaultProperties(Map.of("spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
var context = app.run(args);
show("First polls:");
System.out.println(" processed/orders.csv contains: "
+ Files.readString(processed.resolve("orders.csv")).strip()
.replace("\n", " | "));
Files.writeString(inbox.resolve("orders.csv"), "id,sku\n1,book\n2,pen\n");
Files.writeString(inbox.resolve("returns.csv"), "id,sku\n9,lamp\n");
show("After changing orders.csv and adding returns.csv:");
System.out.println(" still in inbox: " + list(inbox));
context.close();
for (Path dir : new Path[] {inbox, processed}) {
try (var files = Files.list(dir)) {
files.forEach(FileFlow::delete);
}
delete(dir);
}
delete(root);
}
static String list(Path dir) throws IOException {
try (var files = Files.list(dir)) {
return files.map(p -> p.getFileName().toString()).sorted().toList().toString();
}
}
static void delete(Path path) {
try {
Files.delete(path);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
First polls:
customers.csv -> processed/customers.csv
orders.csv -> processed/orders.csv
processed/orders.csv contains: ID,SKU | 1,BOOK
After changing orders.csv and adding returns.csv:
returns.csv -> processed/returns.csv
still in inbox: [customers.csv, orders.csv, readme.txt, returns.csv]
- The inbound adapter picked up
andcustomers.csv , in name order because of the comparator, and skippedorders.csv because ofreadme.txt . EachpatternFilter("*.csv") became one message.File read each file's content into atoStringTransformer() , and the outbound gateway wrote the upper-cased result toString under the original name, taken from theprocessed header. Being a gateway rather than an adapter, it replied with the writtenfile_name , so the flow could continue and report it.File- After
was rewritten with a second line, it was not processed again; only the neworders.csv was. The default filter accepts each file once, and remembers that in memory only, so a restart would process every file in the directory again.returns.csv - The source files stayed in
. The adapter neither moves nor deletes them by itself.inbox
For production, delete or move the source file after it has been handled, for example with .handle(...)file_originalFileFileSystemPersistentAcceptOnceFileListFilterMetadataStore
Choosing channels and patterns
| Need | Use |
|---|---|
| Steps that must run in the caller's thread and transaction | DirectChannel |
| Hand work to a pool and return at once | ExecutorChannel |
| Buffer bursts for a slower consumer | QueueChannel |
| Several independent reactions to one event | PublishSubscribeChannel |
| Plain Java code entering a flow | A gateway interface |
| Parallel processing of the parts of a request | splitaggregategroupTimeout |
| A fallback answer instead of an exception | An error channel on the gateway |
| Failures in asynchronous flows | A flow subscribed to errorChannel |
For a single in-process event with a few listeners, Spring's own