Add cloud-stream module: Spring Cloud Stream 5.1 on Boot 4.2 with Kafka and RabbitMQ binders

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b5uEyg58znuchZ8C8i
This commit is contained in:
asmhatre
2026-11-29 13:20:43 +05:30
co-authored by Claude Sonnet 5.5
parent e54cf840fd
commit e2c42dc268
40 changed files with 1244 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
target/
+61
View File
@@ -0,0 +1,61 @@
# cloud-stream — Spring Cloud Stream on Boot 4.2: functional Kafka and RabbitMQ binders
Companion code for the ankurm.com article *Spring Cloud Stream on Boot 4: Functional Kafka and RabbitMQ Binders*.
One application, three `java.util.function` beans (`Supplier`, `Function`, `Consumer`), run on Kafka and on RabbitMQ by
changing one Spring profile. Every number in the article comes from a file in [`output/`](output), written by the test
suite against real brokers started by Testcontainers, or by the two broker-run scripts.
| Piece | Version | Where it was read from |
|---|---|---|
| Spring Boot | 4.2.0 (GA 19 Nov 2026) | `maven-metadata.xml` |
| Spring Cloud release train | 2026.0.0 | `maven-metadata.xml`; its pom sets `spring-boot.version` to 4.2.0 |
| Spring Cloud Stream / Function | 5.1.0 | `spring-cloud-dependencies` 2026.0.0 pom, startup banner |
| Kafka binder dependencies | spring-kafka 4.2.0, kafka-clients 4.4.0, spring-integration-kafka 7.2.0 | `mvn dependency:tree` |
| Rabbit binder dependencies | spring-rabbit / spring-amqp 4.2.0, amqp-client 5.37.1 | `mvn dependency:tree` |
| Kafka broker | `apache/kafka:4.4.0` (4.4.0) | `kafka-topics.sh --version` in the image |
| RabbitMQ broker | `rabbitmq:4-management` (4.4.1) | `rabbitmqctl --version` in the image |
| Testcontainers | 2.0.5 | Boot's BOM |
| JDK | Temurin 25.0.5.1 | |
## The application
```
orderSource (Supplier) --> orders --> priceOrder (Function) --> invoices --> bill (Consumer)
```
* [`Pipeline.java`](src/main/java/com/ankurm/cloudstream/Pipeline.java): the three beans. No binder import anywhere.
* [`application.yml`](src/main/resources/application.yml): destinations, groups, partitioning and retry, valid for any binder.
* [`application-kafka.yml`](src/main/resources/application-kafka.yml) and [`application-rabbit.yml`](src/main/resources/application-rabbit.yml):
everything that is specific to one broker, including the dead-letter settings.
## Run it
```bash
export JAVA_HOME=/path/to/jdk-25
./scripts/run-all.sh # needs Docker; regenerates every file in output/
```
Against a broker of your own (defaults: Kafka on `localhost:9092`, RabbitMQ on `localhost:5672`):
```bash
mvn -q package -DskipTests
java -jar target/cloud-stream-demo-1.0.jar --spring.profiles.active=kafka --demo.max-orders=8
java -jar target/cloud-stream-demo-1.0.jar --spring.profiles.active=rabbit --demo.max-orders=8
```
## What the tests show
| Test | Transcript | What it demonstrates |
|---|---|---|
| `Test01TestBinderTest` | `01`, `02`, `03` | The test binder: all three function types and the retry count of a failing consumer, with no broker |
| `Test02KafkaPipelineTest` | `04-kafka-pipeline.txt` | The pipeline on Kafka: topics and partitions the binder created, consumer group members, which partition each customer lands in and why |
| `Test03KafkaDlqTest` | `05-kafka-dlq.txt` | `enable-dlq`: attempts, the DLQ topic and its headers |
| `Test04RabbitPipelineTest` | `06-rabbit-partitions.txt` | One queue per partition, what one instance consumes, `required-groups`, and starting the other two instances |
| `Test05RabbitDlqTest` | `07-rabbit-dlq.txt` | `republish-to-dlq` true against false |
| `Test06WiringMistakesTest` | `08`, `09`, `10` | Two binders and no default, no function definition, the `PRECONDITION_FAILED` from mismatched queue arguments |
| `scripts/run-on-broker.sh` | `11-run-kafka.txt`, `12-run-rabbit.txt` | The packaged jar on a real broker; only the profile differs |
| `scripts/binder-free.sh` | `13-binder-free.txt` | The application code names neither broker |
| `scripts/webflux-path.sh` | `14-webflux-path.txt` | The Rabbit binder pulls in WebFlux |
| `scripts/partition-selector.sh` | `15-partition-selector.txt` | The default partition selector, read from the jar: murmur2, not `hashCode()` |
There is no `docs/` folder: the explanations live in the article's own collapsible sections.
@@ -0,0 +1,4 @@
$ function definition = priceOrder (binder: test, no broker)
in orders : {"orderId":"o-1","customerId":"alice","quantity":2,"unitPrice":9.5}
out invoices : {"orderId":"o-1","customerId":"alice","total":19.0}
out contentType header: application/json
@@ -0,0 +1,12 @@
$ function definition = orderSource, poller fixed-delay = 100 ms, demo.max-orders = 5
polled #1: {"orderId":"o-1","customerId":"bob","quantity":2,"unitPrice":9.5}
headers: [contentType, id, scst_partition, timestamp] scst_partition=0
polled #2: {"orderId":"o-2","customerId":"carol","quantity":3,"unitPrice":9.5}
headers: [contentType, id, scst_partition, timestamp] scst_partition=2
polled #3: {"orderId":"o-3","customerId":"dave","quantity":1,"unitPrice":9.5}
headers: [contentType, id, scst_partition, timestamp] scst_partition=1
polled #4: {"orderId":"o-4","customerId":"alice","quantity":2,"unitPrice":9.5}
headers: [contentType, id, scst_partition, timestamp] scst_partition=0
polled #5: {"orderId":"o-5","customerId":"bob","quantity":3,"unitPrice":9.5}
headers: [contentType, id, scst_partition, timestamp] scst_partition=0
messages sent before the supplier started returning null: 5
@@ -0,0 +1,4 @@
$ function definition = bill (max-attempts=3, back-off 200 ms)
good invoice sent -> log lines containing 'bill attempt for o-1': 1
poison invoice sent -> attempts: 3
send() returned normally
+14
View File
@@ -0,0 +1,14 @@
$ profile kafka, supplier capped at 12 orders (demo.max-orders=12), broker apache/kafka:4.4.0
billed lines in the application log: 12
topic invoices-k2 created by the binder with 1 partition(s)
topic orders-k2 created by the binder with 3 partition(s)
consumer group 'pricing': 3 members (concurrency=3), partitions per member [1, 1, 1]
records on orders-k2 by partition (customer of each record):
partition 0: [bob, alice, bob, alice, bob, alice]
partition 1: [dave, dave, dave]
partition 2: [carol, carol, carol]
records that carry a Kafka message key: 0
alice: in 1 partition(s), actually partition 0; murmur2 % 3 = 0, hashCode % 3 = 0
bob: in 1 partition(s), actually partition 0; murmur2 % 3 = 0, hashCode % 3 = 1
carol: in 1 partition(s), actually partition 2; murmur2 % 3 = 2, hashCode % 3 = 1
dave: in 1 partition(s), actually partition 1; murmur2 % 3 = 1, hashCode % 3 = 2
+14
View File
@@ -0,0 +1,14 @@
$ profile kafka, function definition = bill, enable-dlq=true, max-attempts=3
bill attempts: o-1=1 o-2=3 o-3=1
billed: o-1=1 o-2=0 o-3=1 (o-3 was behind the poison record on the same partition)
DLQ topic invoices-k3.billing.dlq holds 1 record(s)
payload: {"orderId":"o-2","customerId":"bob","total":-1.0}
header x-original-topic = invoices-k3
header x-original-partition = 0
header x-original-offset = 1
header x-original-timestamp = (epoch millis, omitted)
header x-original-timestamp-type = CreateTime
header x-exception-fqcn = org.springframework.messaging.MessagingException
header x-exception-message = error occurred in message handler [org.springframework.cloud.stream.function.FunctionConfi...
header x-exception-stacktrace = org.springframework.messaging.MessagingException: Retry policy for operation 'org.springfr...
stack trace mentions the real cause (IllegalArgumentException: Refusing to bill o-2): true
@@ -0,0 +1,17 @@
$ profile rabbit, 12 orders: alice, bob, carol, dave x 3, partition-count=3, consumer instance-count=3 instance-index=0
run A, no required-groups on the orders producer: billed 6 of 12
queues on the broker (name, messages, consumers):
orders-r4a.pricing-0 0 1
run B, required-groups=pricing on the orders producer: billed 6 of 12
queues on the broker (name, messages, consumers):
orders-r4b.pricing-0 0 1
orders-r4b.pricing-1 3 0
orders-r4b.pricing-2 3 0
run C, plus instance-index 1 and 2: billed 12 of 12
queues on the broker (name, messages, consumers):
orders-r4b.pricing-0 0 1
orders-r4b.pricing-1 0 1
orders-r4b.pricing-2 0 1
+25
View File
@@ -0,0 +1,25 @@
$ profile rabbit, function definition = bill, auto-bind-dlq=true, max-attempts=3
--- republish-to-dlq=true (what application-rabbit.yml sets) ---
bill attempts for the poison invoice: 3
queues (name, messages, consumers):
invoices-<run>.billing 0 1
invoices-<run>.billing.dlq 1 0
DLQ payload: {"orderId":"p-r5a","customerId":"alice","total":-1.0}
DLQ header names: [retry-count, x-exception-message, x-exception-stacktrace, x-original-exchange, x-original-routingKey]
x-exception-message = Retry policy for operation 'org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener$$Lambda/0x...' exhausted; aborting execution
x-original-exchange = invoices-<run>
x-original-routingKey = invoices-<run>
DLQ header has x-exception-stacktrace: true
--- republish-to-dlq=false (broker-side dead lettering only) ---
bill attempts for the poison invoice: 3
queues (name, messages, consumers):
invoices-<run>.billing 0 1
invoices-<run>.billing.dlq 1 0
DLQ payload: {"orderId":"p-r5b","customerId":"alice","total":-1.0}
DLQ header names: [x-death, x-first-death-exchange, x-first-death-queue, x-first-death-reason, x-last-death-exchange, x-last-death-queue, x-last-death-reason]
x-first-death-queue = invoices-<run>.billing
x-first-death-reason = rejected
x-death: reason=rejected queue=invoices-<run>.billing count=1
DLQ header has x-exception-stacktrace: false
@@ -0,0 +1,2 @@
$ both binder starters on the classpath, no spring.cloud.stream.default-binder, no per-binding binder
BeanCreationException: Error creating bean with name 'functionInitializer' defined in class path resource [org/springframework/cloud/stream/function/FunctionConfiguration.class]: A default binder has been requested, but there is more than one binder available for 'org.springframework.messaging.MessageChannel' : kafka,rabbit, and no default binder has been set.
@@ -0,0 +1,3 @@
$ three function beans (orderSource, priceOrder, bill), spring.cloud.function.definition left empty
beans of type Function: [functionRouter, priceOrder], Supplier: [orderSource], Consumer: [bill]
send threw NullPointerException: Cannot invoke "org.springframework.messaging.SubscribableChannel.send(org.springframework.messaging.Message)" because the return value of "org.springframework.cloud.stream.binder.test.InputDestination.getChannelByName(String)" is null
@@ -0,0 +1,2 @@
$ rabbit profile, but the producer binding priceOrder-out-0 has required-groups=billing and auto-bind-dlq=false
reply-code=406, reply-text=PRECONDITION_FAILED - inequivalent arg 'x-dead-letter-exchange' for queue 'invoices-<run>.billing' in vhost '/': received the value 'DLX' of type 'longstr' but current is none
+9
View File
@@ -0,0 +1,9 @@
$ docker run <kafka broker> ; java -jar target/cloud-stream-demo-1.0.jar --spring.profiles.active=kafka --demo.max-orders=8 --spring.cloud.stream.kafka.binder.brokers=localhost:19092
com.ankurm.cloudstream.Pipeline : billed o-1 for 19.0
com.ankurm.cloudstream.Pipeline : billed o-2 for 28.5
com.ankurm.cloudstream.Pipeline : billed o-3 for 9.5
com.ankurm.cloudstream.Pipeline : billed o-4 for 19.0
com.ankurm.cloudstream.Pipeline : billed o-5 for 28.5
com.ankurm.cloudstream.Pipeline : billed o-6 for 9.5
com.ankurm.cloudstream.Pipeline : billed o-7 for 19.0
com.ankurm.cloudstream.Pipeline : billed o-8 for 28.5
+5
View File
@@ -0,0 +1,5 @@
$ docker run <rabbit broker> ; java -jar target/cloud-stream-demo-1.0.jar --spring.profiles.active=rabbit --demo.max-orders=8 --spring.rabbitmq.port=25672
com.ankurm.cloudstream.Pipeline : billed o-1 for 19.0
com.ankurm.cloudstream.Pipeline : billed o-4 for 19.0
com.ankurm.cloudstream.Pipeline : billed o-5 for 28.5
com.ankurm.cloudstream.Pipeline : billed o-8 for 28.5
+16
View File
@@ -0,0 +1,16 @@
$ grep -rilE 'kafka|rabbit' src/main/java | wc -l
0
$ grep -rilE 'kafka|rabbit' src/main/resources
src/main/resources/application-kafka.yml
src/main/resources/application-rabbit.yml
$ grep -E 'import' src/main/java/com/ankurm/cloudstream/Pipeline.java
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+6
View File
@@ -0,0 +1,6 @@
$ mvn dependency:tree -Dincludes=org.springframework.boot:spring-boot-starter-webflux
com.ankurm:cloud-stream-demo:jar:1.0
\- org.springframework.cloud:spring-cloud-starter-stream-rabbit:jar:5.1.0:compile
\- org.springframework.cloud:spring-cloud-stream-binder-rabbit:jar:5.1.0:compile
\- org.springframework.cloud:spring-cloud-stream-binder-rabbit-core:jar:5.1.0:compile
\- org.springframework.boot:spring-boot-starter-webflux:jar:4.2.0:compile
@@ -0,0 +1,14 @@
$ javap -p -c PartitionHandler$DefaultPartitionSelector (selectPartition and the murmur2 call)
public int selectPartition(java.lang.Object, int);
Code:
0: aload_1
1: invokevirtual #7 // Method java/lang/Object.toString:()Ljava/lang/String;
4: getstatic #11 // Field java/nio/charset/StandardCharsets.UTF_8:Ljava/nio/charset/Charset;
7: invokevirtual #17 // Method java/lang/String.getBytes:(Ljava/nio/charset/Charset;)[B
10: astore_3
11: aload_0
12: aload_3
13: invokevirtual #23 // Method murmur2:([B)I
16: ldc #29 // int 2147483647
18: iand
19: ireturn
+83
View File
@@ -0,0 +1,83 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>cloud-stream-demo</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<java.version>25</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Spring Cloud 2026.0.0 is the release train built on Boot 4.2 (its pom sets spring-boot.version=4.2.0)
and carries Spring Cloud Stream 5.1.0. -->
<spring-cloud.version>2026.0.0</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Both binders are on the classpath on purpose: the application code never imports either one, and
spring.cloud.stream.default-binder (set per profile) decides which one is used. -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-test-binder</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-rabbitmq</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-kafka</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Shows that the application code does not mention either broker; only configuration does.
cd "$(dirname "$0")/.."
echo "\$ grep -rilE 'kafka|rabbit' src/main/java | wc -l"
grep -rilE 'kafka|rabbit' src/main/java | wc -l
echo "\$ grep -rilE 'kafka|rabbit' src/main/resources"
grep -rilE 'kafka|rabbit' src/main/resources | sort
echo "\$ grep -E 'import' src/main/java/com/ankurm/cloudstream/Pipeline.java"
grep -E '^import' src/main/java/com/ankurm/cloudstream/Pipeline.java
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Reads the default partition selector out of the shipped jar, because the reference page and the jar disagree.
set -eu
cd "$(dirname "$0")/.."
JAR=$(find "${HOME}/.m2" -name 'spring-cloud-stream-5.1.0.jar' | head -1)
echo '$ javap -p -c PartitionHandler$DefaultPartitionSelector (selectPartition and the murmur2 call)'
javap -p -c -cp "$JAR" 'org.springframework.cloud.stream.binder.PartitionHandler$DefaultPartitionSelector' 2>/dev/null \
| sed -n '/public int selectPartition/,/ireturn/p' | sed -E 's/^ +//'
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Regenerates every file under output/. Needs JDK 25, Maven and a running Docker daemon
# (Testcontainers starts apache/kafka:4.4.0 and rabbitmq:4-management; the broker runs need free ports 9092 and 5672).
set -eu
cd "$(dirname "$0")/.."
mkdir -p output
mvn -B -q test # writes output/01..10
./scripts/binder-free.sh > output/13-binder-free.txt
./scripts/webflux-path.sh > output/14-webflux-path.txt
./scripts/partition-selector.sh > output/15-partition-selector.txt
mvn -B -q package -DskipTests
./scripts/run-on-broker.sh kafka > output/11-run-kafka.txt
./scripts/run-on-broker.sh rabbit > output/12-run-rabbit.txt
ls -1 output
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Runs the packaged application against a real broker started with plain `docker run`, switching ONLY the Spring profile.
# ./scripts/run-on-broker.sh kafka > output/11-run-kafka.txt
# ./scripts/run-on-broker.sh rabbit > output/12-run-rabbit.txt
# Needs Docker and a built jar (mvn -q package -DskipTests).
set -eu
cd "$(dirname "$0")/.."
BINDER="${1:?usage: run-on-broker.sh kafka|rabbit}"
JAR=$(ls target/cloud-stream-demo-*.jar | head -1)
NAME="cs-demo-$BINDER"
docker rm -f "$NAME" > /dev/null 2>&1 || true
case "$BINDER" in
# Non-default host ports so the script does not collide with a broker you already have on 9092 or 5672.
kafka) docker run -d --name "$NAME" -p 19092:9092 \
-e KAFKA_NODE_ID=1 -e KAFKA_PROCESS_ROLES=broker,controller \
-e KAFKA_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093 -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:19092 \
-e KAFKA_CONTROLLER_LISTENER_NAMES=CONTROLLER -e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT \
-e KAFKA_CONTROLLER_QUORUM_VOTERS=1@localhost:9093 -e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 \
-e KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=1 -e KAFKA_TRANSACTION_STATE_LOG_MIN_ISR=1 \
apache/kafka:4.4.0 > /dev/null
READY=19092; BROKER_ARG="--spring.cloud.stream.kafka.binder.brokers=localhost:19092" ;;
rabbit) docker run -d --name "$NAME" -p 25672:5672 rabbitmq:4-management > /dev/null
READY=25672; BROKER_ARG="--spring.rabbitmq.port=25672" ;;
*) echo "kafka or rabbit" >&2; exit 2 ;;
esac
trap 'docker rm -f "$NAME" > /dev/null 2>&1 || true' EXIT
for _ in $(seq 1 90); do (echo > /dev/tcp/127.0.0.1/$READY) 2>/dev/null && break; sleep 1; done
[ "$BINDER" = rabbit ] && sleep 15 || sleep 8 # the port opens before the broker is ready to serve
echo "\$ docker run <$BINDER broker> ; java -jar target/cloud-stream-demo-1.0.jar --spring.profiles.active=$BINDER --demo.max-orders=8 $BROKER_ARG"
LOG=$(mktemp)
java -jar "$JAR" --spring.profiles.active="$BINDER" --demo.max-orders=8 "$BROKER_ARG" > "$LOG" 2>&1 &
APP=$!
sleep 40
kill "$APP" 2>/dev/null || true; wait "$APP" 2>/dev/null || true
grep -E "billed o-" "$LOG" | sed -E 's/^.* INFO [0-9]+ --- \[[^]]*\] \[[^]]*\] //' | sort -t' ' -k5 -V
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Which dependency pulls WebFlux into a project that only asked for the two binder starters?
set -eu
cd "$(dirname "$0")/.."
echo '$ mvn dependency:tree -Dincludes=org.springframework.boot:spring-boot-starter-webflux'
mvn -B -q dependency:tree -Dincludes=org.springframework.boot:spring-boot-starter-webflux -DoutputFile=/dev/stdout 2>/dev/null | sed -n '1,8p'
@@ -0,0 +1,12 @@
package com.ankurm.cloudstream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CloudStreamApplication {
public static void main(String[] args) {
SpringApplication.run(CloudStreamApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package com.ankurm.cloudstream;
/** What the function emits and the consumer receives. */
public record Invoice(String orderId, String customerId, double total) {
}
@@ -0,0 +1,5 @@
package com.ankurm.cloudstream;
/** What the supplier emits and the function consumes. Serialized as JSON by Spring Cloud Stream. */
public record Order(String orderId, String customerId, int quantity, double unitPrice) {
}
@@ -0,0 +1,62 @@
package com.ankurm.cloudstream;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The whole application: three plain java.util.function beans. Nothing here imports a binder or a
* broker client, which is what makes switching brokers a configuration change.
*
* <pre>
* orderSource (Supplier) --&gt; orders --&gt; priceOrder (Function) --&gt; invoices --&gt; bill (Consumer)
* </pre>
*/
@Configuration(proxyBeanMethods = false)
public class Pipeline {
private static final Logger log = LoggerFactory.getLogger(Pipeline.class);
private static final List<String> CUSTOMERS = List.of("alice", "bob", "carol", "dave");
/**
* Polled by the framework (every second by default), one order per call. A supplier that returns
* {@code null} sends nothing, which is how {@code demo.max-orders} makes the demos finite (0 = unbounded).
*/
@Bean
public Supplier<Order> orderSource(@Value("${demo.max-orders:0}") int maxOrders) {
AtomicInteger n = new AtomicInteger();
return () -> {
int i = n.incrementAndGet();
if (maxOrders > 0 && i > maxOrders) {
return null;
}
return new Order("o-" + i, CUSTOMERS.get(i % CUSTOMERS.size()), 1 + i % 3, 9.5);
};
}
/** Input and output are both typed; the framework converts JSON to and from the records. */
@Bean
public Function<Order, Invoice> priceOrder() {
return order -> new Invoice(order.orderId(), order.customerId(), order.quantity() * order.unitPrice());
}
/** A negative total is the "poison" in the dead-letter demos: this consumer throws on it. */
@Bean
public Consumer<Invoice> bill() {
return invoice -> {
log.info("bill attempt for {}", invoice.orderId());
if (invoice.total() < 0) {
throw new IllegalArgumentException("Refusing to bill " + invoice.orderId() + ": negative total");
}
log.info("billed {} for {}", invoice.orderId(), invoice.total());
};
}
}
@@ -0,0 +1,14 @@
spring:
cloud:
stream:
default-binder: kafka
bindings:
priceOrder-in-0:
consumer:
concurrency: 3
kafka:
bindings:
bill-in-0:
consumer:
enable-dlq: true
dlq-name: invoices.billing.dlq
@@ -0,0 +1,27 @@
spring:
cloud:
stream:
default-binder: rabbit
bindings:
priceOrder-out-0:
producer:
# Rabbit routes through an exchange: a message published before the group's queue exists is
# dropped. required-groups makes the producer declare the consumer queue itself.
required-groups: billing
priceOrder-in-0:
consumer:
# Rabbit has no consumer groups across partitions: every instance owns exactly one partition queue.
partitioned: true
instance-count: 3
instance-index: 0
rabbit:
bindings:
priceOrder-out-0:
producer:
# The producer declares the consumer's queue for required-groups, so it must declare it with
# the same arguments as the consumer does, or the broker answers PRECONDITION_FAILED.
auto-bind-dlq: true
bill-in-0:
consumer:
auto-bind-dlq: true
republish-to-dlq: true
@@ -0,0 +1,37 @@
# Everything broker-neutral lives in this file. The broker-specific blocks live in the two
# profile files next to it.
spring:
application.name: cloud-stream-demo
main:
# The Rabbit binder drags spring-boot-starter-webflux in transitively, which would turn this broker-only
# worker into a reactive web server on port 8080 (see scripts/webflux-path.sh).
web-application-type: none
cloud:
function:
# The functions to bind, separated by semicolons. Left empty, nothing was bound to 'orders' (output/09).
definition: orderSource;priceOrder;bill
stream:
poller:
fixed-delay: 1000
bindings:
orderSource-out-0:
destination: orders
producer:
partition-key-expression: payload.customerId
partition-count: 3
priceOrder-in-0:
destination: orders
group: pricing
priceOrder-out-0:
destination: invoices
bill-in-0:
destination: invoices
group: billing
consumer:
max-attempts: 3
back-off-initial-interval: 200
back-off-multiplier: 1.0
logging:
level:
root: WARN
com.ankurm: INFO
@@ -0,0 +1,25 @@
package com.ankurm.cloudstream;
import java.time.Duration;
import java.util.function.BooleanSupplier;
final class Await {
private Await() {
}
static boolean until(Duration max, BooleanSupplier condition) {
long end = System.nanoTime() + max.toNanos();
while (System.nanoTime() < end) {
if (condition.getAsBoolean()) {
return true;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
return condition.getAsBoolean();
}
}
@@ -0,0 +1,120 @@
package com.ankurm.cloudstream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import org.testcontainers.kafka.KafkaContainer;
import org.testcontainers.rabbitmq.RabbitMQContainer;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/** Lazily started singleton brokers shared by every test class in the run. */
public final class Brokers {
public static final String KAFKA_IMAGE = "apache/kafka:4.4.0";
public static final String RABBIT_IMAGE = "rabbitmq:4-management";
private static final JsonMapper JSON = JsonMapper.builder().build();
private static final HttpClient HTTP = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
private static KafkaContainer kafka;
private static RabbitMQContainer rabbit;
private Brokers() {
}
public static synchronized KafkaContainer kafka() {
if (kafka == null) {
kafka = new KafkaContainer(KAFKA_IMAGE);
kafka.start();
}
return kafka;
}
public static synchronized RabbitMQContainer rabbit() {
if (rabbit == null) {
rabbit = new RabbitMQContainer(RABBIT_IMAGE);
rabbit.start();
}
return rabbit;
}
/** Broker coordinates as command-line style properties, in the form Spring Boot and the binders read them. */
public static String[] kafkaProps() {
return new String[] {"spring.cloud.stream.kafka.binder.brokers=" + kafka().getBootstrapServers()};
}
public static String[] rabbitProps() {
RabbitMQContainer r = rabbit();
return new String[] {"spring.rabbitmq.host=" + r.getHost(), "spring.rabbitmq.port=" + r.getAmqpPort(),
"spring.rabbitmq.username=" + r.getAdminUsername(), "spring.rabbitmq.password=" + r.getAdminPassword()};
}
/** Destination, DLQ and group names get a suffix so each test class works on its own topics and queues. */
public static String[] suffixed(String suffix) {
return new String[] {
"spring.cloud.stream.bindings.orderSource-out-0.destination=orders-" + suffix,
"spring.cloud.stream.bindings.priceOrder-in-0.destination=orders-" + suffix,
"spring.cloud.stream.bindings.priceOrder-out-0.destination=invoices-" + suffix,
"spring.cloud.stream.bindings.bill-in-0.destination=invoices-" + suffix,
"spring.cloud.stream.kafka.bindings.bill-in-0.consumer.dlq-name=invoices-" + suffix + ".billing.dlq"};
}
public static String[] concat(String[]... parts) {
return java.util.stream.Stream.of(parts).flatMap(java.util.stream.Stream::of).toArray(String[]::new);
}
// ---- RabbitMQ management API helpers --------------------------------------------------------------------
private static HttpRequest.Builder request(String path) {
RabbitMQContainer r = rabbit();
String auth = Base64.getEncoder().encodeToString((r.getAdminUsername() + ":" + r.getAdminPassword()).getBytes());
return HttpRequest.newBuilder(URI.create("http://" + r.getHost() + ":" + r.getMappedPort(15672) + "/api" + path))
.header("Authorization", "Basic " + auth).header("Content-Type", "application/json");
}
public static JsonNode mgmtGet(String path) {
try {
return JSON.readTree(HTTP.send(request(path).GET().build(), HttpResponse.BodyHandlers.ofString()).body());
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static JsonNode mgmtPost(String path, String body) {
try {
return JSON.readTree(HTTP.send(request(path).POST(HttpRequest.BodyPublishers.ofString(body)).build(),
HttpResponse.BodyHandlers.ofString()).body());
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
/** Messages (ready + unacked) as rabbitmqctl reports them, or -1 when the queue does not exist. */
public static int depth(String queue) {
try {
String out = rabbit().execInContainer("rabbitmqctl", "-q", "list_queues", "name", "messages").getStdout();
for (String line : out.split("\n")) {
String[] c = line.split("\\s+");
if (c.length == 2 && c[0].equals(queue)) {
return Integer.parseInt(c[1]);
}
}
return -1;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static String listQueues(String prefix) {
try {
String out = rabbit().execInContainer("rabbitmqctl", "-q", "list_queues", "name", "messages", "consumers").getStdout();
return java.util.Arrays.stream(out.split("\n")).filter(l -> l.startsWith(prefix)).sorted()
.collect(java.util.stream.Collectors.joining("\n"));
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,108 @@
package com.ankurm.cloudstream;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.cloud.stream.binder.test.InputDestination;
import org.springframework.cloud.stream.binder.test.OutputDestination;
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
/**
* The test binder replaces Kafka and RabbitMQ with in-memory destinations, so the three function
* types can be exercised with no broker and no Docker. The same CloudStreamApplication is used: only
* the binder changes.
*/
@ExtendWith(OutputCaptureExtension.class)
class Test01TestBinderTest {
private static ConfigurableApplicationContext start(String... args) {
return new SpringApplicationBuilder(TestChannelBinderConfiguration.getCompleteConfiguration(CloudStreamApplication.class))
.web(WebApplicationType.NONE).run(args);
}
private static Message<byte[]> json(String s) {
return MessageBuilder.withPayload(s.getBytes()).build();
}
@Test
void function() {
try (Transcript t = new Transcript("01-test-binder-function");
ConfigurableApplicationContext ctx = start("--spring.cloud.function.definition=priceOrder")) {
InputDestination in = ctx.getBean(InputDestination.class);
OutputDestination out = ctx.getBean(OutputDestination.class);
t.line("$ function definition = priceOrder (binder: test, no broker)");
in.send(json("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"quantity\":2,\"unitPrice\":9.5}"), "orders");
Message<byte[]> reply = out.receive(2000, "invoices");
t.line("in orders : {\"orderId\":\"o-1\",\"customerId\":\"alice\",\"quantity\":2,\"unitPrice\":9.5}");
t.line("out invoices : %s", new String(reply.getPayload()));
t.line("out contentType header: %s", reply.getHeaders().get("contentType"));
assertThat(new String(reply.getPayload())).isEqualTo("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"total\":19.0}");
}
}
@Test
void supplier() {
try (Transcript t = new Transcript("02-test-binder-supplier");
ConfigurableApplicationContext ctx = start("--spring.cloud.function.definition=orderSource",
"--spring.cloud.stream.poller.fixed-delay=100", "--demo.max-orders=5")) {
OutputDestination out = ctx.getBean(OutputDestination.class);
t.line("$ function definition = orderSource, poller fixed-delay = 100 ms, demo.max-orders = 5");
List<String> got = new ArrayList<>();
Message<byte[]> m;
while ((m = out.receive(1500, "orders")) != null) {
got.add(new String(m.getPayload()));
t.line("polled #%d: %s", got.size(), got.get(got.size() - 1));
t.line(" headers: %s scst_partition=%s", new java.util.TreeSet<>(m.getHeaders().keySet()), m.getHeaders().get("scst_partition"));
}
t.line("messages sent before the supplier started returning null: %d", got.size());
assertThat(got).hasSize(5);
}
}
@Test
void consumer(CapturedOutput output) {
try (Transcript t = new Transcript("03-test-binder-consumer");
ConfigurableApplicationContext ctx = start("--spring.cloud.function.definition=bill")) {
InputDestination in = ctx.getBean(InputDestination.class);
t.line("$ function definition = bill (max-attempts=3, back-off 200 ms)");
in.send(json("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"total\":19.0}"), "invoices");
t.line("good invoice sent -> log lines containing 'bill attempt for o-1': %d", count(output, "bill attempt for o-1"));
String poisonResult;
try {
in.send(json("{\"orderId\":\"o-2\",\"customerId\":\"bob\",\"total\":-1.0}"), "invoices");
poisonResult = "send() returned normally";
} catch (Exception e) {
poisonResult = "send() threw " + e.getClass().getSimpleName() + ": " + rootMessage(e);
}
t.line("poison invoice sent -> attempts: %d", count(output, "bill attempt for o-2"));
t.line("%s", poisonResult);
}
}
static int count(CapturedOutput output, String needle) {
String s = output.getAll();
int n = 0;
for (int i = s.indexOf(needle); i >= 0; i = s.indexOf(needle, i + 1)) {
n++;
}
return n;
}
static String rootMessage(Throwable e) {
while (e.getCause() != null) {
e = e.getCause();
}
return e.getMessage();
}
}
@@ -0,0 +1,102 @@
package com.ankurm.cloudstream;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.TopicDescription;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.ConfigurableApplicationContext;
/** The whole pipeline, supplier to consumer, on a real Kafka broker (apache/kafka in Testcontainers). */
@ExtendWith(OutputCaptureExtension.class)
class Test02KafkaPipelineTest {
@Test
void pipelineAndPartitions(CapturedOutput output) throws Exception {
String bootstrap = Brokers.kafka().getBootstrapServers();
try (Transcript t = new Transcript("04-kafka-pipeline");
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(CloudStreamApplication.class)
.web(WebApplicationType.NONE)
.run(Brokers.concat(new String[] {"--spring.profiles.active=kafka", "--demo.max-orders=12"},
prefixed(Brokers.kafkaProps()), prefixed(Brokers.suffixed("k2"))))) {
t.line("$ profile kafka, supplier capped at 12 orders (demo.max-orders=12), broker %s", Brokers.KAFKA_IMAGE);
assertThat(Await.until(Duration.ofSeconds(60), () -> Test01TestBinderTest.count(output, "billed o-") == 12)).isTrue();
t.line("billed lines in the application log: %d", Test01TestBinderTest.count(output, "billed o-"));
try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
Map<String, TopicDescription> topics = admin.describeTopics(List.of("orders-k2", "invoices-k2")).allTopicNames().get();
for (String name : new TreeSet<>(topics.keySet())) {
t.line("topic %s created by the binder with %d partition(s)", name, topics.get(name).partitions().size());
}
assertThat(topics.get("orders-k2").partitions()).hasSize(3);
assertThat(topics.get("invoices-k2").partitions()).hasSize(1);
var group = admin.describeConsumerGroups(List.of("pricing")).all().get().get("pricing");
t.line("consumer group 'pricing': %d members (concurrency=3), partitions per member %s", group.members().size(),
group.members().stream().map(m -> m.assignment().topicPartitions().size()).sorted().toList());
assertThat(group.members()).hasSize(3);
}
Properties p = new Properties();
p.put("bootstrap.servers", bootstrap);
p.put("key.deserializer", StringDeserializer.class.getName());
p.put("value.deserializer", StringDeserializer.class.getName());
p.put("group.id", "inspector-" + System.nanoTime());
Map<Integer, List<String>> byPartition = new TreeMap<>();
int keyed = 0;
try (KafkaConsumer<String, String> c = new KafkaConsumer<>(p)) {
List<TopicPartition> tps = List.of(new TopicPartition("orders-k2", 0), new TopicPartition("orders-k2", 1),
new TopicPartition("orders-k2", 2));
c.assign(tps);
c.seekToBeginning(tps);
for (ConsumerRecord<String, String> r : c.poll(Duration.ofSeconds(5))) {
byPartition.computeIfAbsent(r.partition(), k -> new ArrayList<>())
.add(r.value().replaceAll(".*\"customerId\":\"(\\w+)\".*", "$1"));
if (r.key() != null) {
keyed++;
}
}
}
t.line("records on orders-k2 by partition (customer of each record):");
byPartition.forEach((part, customers) -> t.line(" partition %d: %s", part, customers));
t.line("records that carry a Kafka message key: %d", keyed);
for (String customer : List.of("alice", "bob", "carol", "dave")) {
long partitions = byPartition.values().stream().filter(l -> l.contains(customer)).count();
int murmur = org.apache.kafka.common.utils.Utils.toPositive(
org.apache.kafka.common.utils.Utils.murmur2(customer.getBytes(java.nio.charset.StandardCharsets.UTF_8))) % 3;
int hash = Math.abs(customer.hashCode()) % 3;
int actual = byPartition.entrySet().stream().filter(e -> e.getValue().contains(customer)).findFirst().get().getKey();
t.line("%s: in %d partition(s), actually partition %d; murmur2 %% 3 = %d, hashCode %% 3 = %d", customer, partitions,
actual, murmur, hash);
assertThat(partitions).isEqualTo(1);
assertThat(actual).isEqualTo(murmur);
}
assertThat(byPartition.values().stream().mapToInt(List::size).sum()).isEqualTo(12);
assertThat(keyed).isZero();
}
}
/** Spring Boot command-line arguments need the leading dashes. */
static String[] prefixed(String[] props) {
return java.util.Arrays.stream(props).map(s -> "--" + s).toArray(String[]::new);
}
}
@@ -0,0 +1,90 @@
package com.ankurm.cloudstream;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.ConfigurableApplicationContext;
/** Dead-letter handling with the Kafka binder: enable-dlq republishes a failed record to a DLQ topic. */
@ExtendWith(OutputCaptureExtension.class)
class Test03KafkaDlqTest {
@Test
void poisonGoesToTheDlqTopic(CapturedOutput output) throws Exception {
try (Transcript t = new Transcript("05-kafka-dlq");
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(CloudStreamApplication.class)
.web(WebApplicationType.NONE)
.run(Brokers.concat(new String[] {"--spring.profiles.active=kafka",
"--spring.cloud.function.definition=bill"},
Test02KafkaPipelineTest.prefixed(Brokers.kafkaProps()),
Test02KafkaPipelineTest.prefixed(Brokers.suffixed("k3"))))) {
StreamBridge bridge = ctx.getBean(StreamBridge.class);
t.line("$ profile kafka, function definition = bill, enable-dlq=true, max-attempts=3");
bridge.send("invoices-k3", new Invoice("o-1", "alice", 19.0));
bridge.send("invoices-k3", new Invoice("o-2", "bob", -1.0));
bridge.send("invoices-k3", new Invoice("o-3", "carol", 9.5));
assertThat(Await.until(Duration.ofSeconds(30), () -> Test01TestBinderTest.count(output, "billed o-3") == 1)).isTrue();
assertThat(Await.until(Duration.ofSeconds(30), () -> Test01TestBinderTest.count(output, "bill attempt for o-2") == 3)).isTrue();
t.line("bill attempts: o-1=%d o-2=%d o-3=%d", Test01TestBinderTest.count(output, "bill attempt for o-1"),
Test01TestBinderTest.count(output, "bill attempt for o-2"), Test01TestBinderTest.count(output, "bill attempt for o-3"));
t.line("billed: o-1=%d o-2=%d o-3=%d (o-3 was behind the poison record on the same partition)",
Test01TestBinderTest.count(output, "billed o-1"), Test01TestBinderTest.count(output, "billed o-2"),
Test01TestBinderTest.count(output, "billed o-3"));
Properties p = new Properties();
p.put("bootstrap.servers", Brokers.kafka().getBootstrapServers());
p.put("key.deserializer", StringDeserializer.class.getName());
p.put("value.deserializer", StringDeserializer.class.getName());
p.put("group.id", "inspector-" + System.nanoTime());
p.put("auto.offset.reset", "earliest");
List<ConsumerRecord<String, String>> dead = new java.util.ArrayList<>();
try (KafkaConsumer<String, String> c = new KafkaConsumer<>(p)) {
c.subscribe(List.of("invoices-k3.billing.dlq"));
Await.until(Duration.ofSeconds(20), () -> {
c.poll(Duration.ofMillis(500)).forEach(dead::add);
return !dead.isEmpty();
});
}
assertThat(dead).hasSize(1);
ConsumerRecord<String, String> r = dead.get(0);
t.line("DLQ topic invoices-k3.billing.dlq holds %d record(s)", dead.size());
t.line("payload: %s", r.value());
for (Header h : r.headers()) {
if (!h.key().startsWith("x-")) {
continue;
}
String v = switch (h.key()) {
case "x-original-partition" -> String.valueOf(java.nio.ByteBuffer.wrap(h.value()).getInt());
case "x-original-offset", "x-original-timestamp" -> String.valueOf(java.nio.ByteBuffer.wrap(h.value()).getLong());
default -> new String(h.value(), StandardCharsets.UTF_8).replace("\n", " ").replaceAll("Lambda/0x[0-9a-f]+", "Lambda/0x...");
};
if (h.key().equals("x-original-timestamp")) {
v = "(epoch millis, omitted)";
}
t.line("header %s = %s", h.key(), v.length() > 90 ? v.substring(0, 90) + "..." : v);
if (h.key().equals("x-exception-stacktrace")) {
String full = new String(h.value(), StandardCharsets.UTF_8);
t.line(" stack trace mentions the real cause (IllegalArgumentException: Refusing to bill o-2): %s",
full.contains("java.lang.IllegalArgumentException: Refusing to bill o-2"));
assertThat(full).contains("java.lang.IllegalArgumentException: Refusing to bill o-2");
}
}
assertThat(r.value()).contains("o-2");
}
}
}
@@ -0,0 +1,79 @@
package com.ankurm.cloudstream;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.ConfigurableApplicationContext;
/**
* The same pipeline on RabbitMQ. Rabbit has no partitions inside a queue: the binder fakes them with one queue per
* partition (orders.pricing-0, -1, -2) and each consumer instance owns exactly one of them.
*/
@ExtendWith(OutputCaptureExtension.class)
class Test04RabbitPipelineTest {
private static ConfigurableApplicationContext start(String suffix, int index, String definition, String... extra) {
return new SpringApplicationBuilder(CloudStreamApplication.class).web(WebApplicationType.NONE)
.run(Brokers.concat(new String[] {"--spring.profiles.active=rabbit", "--demo.max-orders=12",
"--spring.cloud.function.definition=" + definition,
"--spring.cloud.stream.bindings.priceOrder-in-0.consumer.instance-index=" + index},
Test02KafkaPipelineTest.prefixed(Brokers.rabbitProps()),
Test02KafkaPipelineTest.prefixed(Brokers.suffixed(suffix)), extra));
}
@Test
void oneInstanceOwnsOneQueue(CapturedOutput output) throws Exception {
try (Transcript t = new Transcript("06-rabbit-partitions")) {
t.line("$ profile rabbit, 12 orders: alice, bob, carol, dave x 3, partition-count=3, consumer instance-count=3 instance-index=0");
// Run A: the producer declares only the exchange, so a partition with no queue yet is dropped.
int before = Test01TestBinderTest.count(output, "billed o-");
try (ConfigurableApplicationContext a = start("r4a", 0, "orderSource;priceOrder;bill")) {
Await.until(Duration.ofSeconds(20), () -> Test01TestBinderTest.count(output, "billed o-") - before >= 6);
Thread.sleep(3000);
t.line("");
t.line("run A, no required-groups on the orders producer: billed %d of 12", Test01TestBinderTest.count(output, "billed o-") - before);
t.line("queues on the broker (name, messages, consumers):");
Brokers.listQueues("orders-r4a").lines().forEach(l -> t.line(" %s", l));
assertThat(Test01TestBinderTest.count(output, "billed o-") - before).isEqualTo(6);
}
// Run B: required-groups makes the producer declare every partition queue up front.
int beforeB = Test01TestBinderTest.count(output, "billed o-");
List<ConfigurableApplicationContext> extras = new ArrayList<>();
try (ConfigurableApplicationContext b = start("r4b", 0, "orderSource;priceOrder;bill",
"--spring.cloud.stream.bindings.orderSource-out-0.producer.required-groups=pricing")) {
Await.until(Duration.ofSeconds(20), () -> Test01TestBinderTest.count(output, "billed o-") - beforeB >= 6);
Thread.sleep(3000);
t.line("");
t.line("run B, required-groups=pricing on the orders producer: billed %d of 12", Test01TestBinderTest.count(output, "billed o-") - beforeB);
t.line("queues on the broker (name, messages, consumers):");
Brokers.listQueues("orders-r4b").lines().forEach(l -> t.line(" %s", l));
assertThat(Brokers.depth("orders-r4b.pricing-1")).isEqualTo(3);
assertThat(Brokers.depth("orders-r4b.pricing-2")).isEqualTo(3);
// Run C: two more instances, one per remaining partition queue.
extras.add(start("r4b", 1, "priceOrder"));
extras.add(start("r4b", 2, "priceOrder"));
Await.until(Duration.ofSeconds(30), () -> Test01TestBinderTest.count(output, "billed o-") - beforeB == 12);
Thread.sleep(2000);
t.line("");
t.line("run C, plus instance-index 1 and 2: billed %d of 12", Test01TestBinderTest.count(output, "billed o-") - beforeB);
t.line("queues on the broker (name, messages, consumers):");
Brokers.listQueues("orders-r4b").lines().forEach(l -> t.line(" %s", l));
assertThat(Test01TestBinderTest.count(output, "billed o-") - beforeB).isEqualTo(12);
} finally {
extras.forEach(ConfigurableApplicationContext::close);
}
}
}
}
@@ -0,0 +1,72 @@
package com.ankurm.cloudstream;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.TreeSet;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.ConfigurableApplicationContext;
import tools.jackson.databind.JsonNode;
/** Dead-lettering with the Rabbit binder, with and without republish-to-dlq. */
@ExtendWith(OutputCaptureExtension.class)
class Test05RabbitDlqTest {
private static ConfigurableApplicationContext start(String suffix, String... extra) {
return new SpringApplicationBuilder(CloudStreamApplication.class).web(WebApplicationType.NONE)
.run(Brokers.concat(new String[] {"--spring.profiles.active=rabbit", "--spring.cloud.function.definition=bill"},
Test02KafkaPipelineTest.prefixed(Brokers.rabbitProps()),
Test02KafkaPipelineTest.prefixed(Brokers.suffixed(suffix)), extra));
}
private void poisonRun(Transcript t, CapturedOutput output, String suffix, String label, String... extra) throws Exception {
t.line("");
t.line("--- %s ---", label);
try (ConfigurableApplicationContext ctx = start(suffix, extra)) {
StreamBridge bridge = ctx.getBean(StreamBridge.class);
bridge.send("invoices-" + suffix, new Invoice("p-" + suffix, "alice", -1.0));
bridge.send("invoices-" + suffix, new Invoice("g-" + suffix, "bob", 9.5));
assertThat(Await.until(Duration.ofSeconds(30), () -> Test01TestBinderTest.count(output, "billed g-" + suffix) == 1)).isTrue();
assertThat(Await.until(Duration.ofSeconds(30), () -> Brokers.depth("invoices-" + suffix + ".billing.dlq") == 1)).isTrue();
t.line("bill attempts for the poison invoice: %d", Test01TestBinderTest.count(output, "bill attempt for p-" + suffix));
t.line("queues (name, messages, consumers):");
Brokers.listQueues("invoices-" + suffix).lines().forEach(l -> t.line(" %s", l.replace(suffix, "<run>")));
JsonNode msgs = Brokers.mgmtPost("/queues/%2F/invoices-" + suffix + ".billing.dlq/get",
"{\"count\":1,\"ackmode\":\"ack_requeue_true\",\"encoding\":\"auto\"}");
JsonNode m = msgs.get(0);
t.line("DLQ payload: %s", m.path("payload").asString());
TreeSet<String> headers = new TreeSet<>(m.path("properties").path("headers").propertyNames());
t.line("DLQ header names: %s", headers);
for (String h : headers) {
if (h.equals("x-exception-message") || h.equals("x-original-exchange") || h.equals("x-original-routingKey")
|| h.equals("x-first-death-reason") || h.equals("x-first-death-queue")) {
t.line(" %s = %s", h, m.path("properties").path("headers").path(h).asString().replace(suffix, "<run>")
.replaceAll("Lambda/0x[0-9a-f]+", "Lambda/0x..."));
}
}
if (headers.contains("x-death")) {
JsonNode death = m.path("properties").path("headers").path("x-death").get(0);
t.line(" x-death: reason=%s queue=%s count=%d", death.path("reason").asString(),
death.path("queue").asString().replace(suffix, "<run>"), death.path("count").asInt());
}
t.line("DLQ header has x-exception-stacktrace: %s", headers.contains("x-exception-stacktrace"));
}
}
@Test
void republishVersusPlainDeadLettering(CapturedOutput output) throws Exception {
try (Transcript t = new Transcript("07-rabbit-dlq")) {
t.line("$ profile rabbit, function definition = bill, auto-bind-dlq=true, max-attempts=3");
poisonRun(t, output, "r5a", "republish-to-dlq=true (what application-rabbit.yml sets)");
poisonRun(t, output, "r5b", "republish-to-dlq=false (broker-side dead lettering only)",
"--spring.cloud.stream.rabbit.bindings.bill-in-0.consumer.republish-to-dlq=false");
}
}
}
@@ -0,0 +1,85 @@
package com.ankurm.cloudstream;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.cloud.stream.binder.test.InputDestination;
import org.springframework.cloud.stream.binder.test.OutputDestination;
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
/** Three ways the wiring goes wrong, each with the symptom the framework really produces. */
@ExtendWith(OutputCaptureExtension.class)
class Test06WiringMistakesTest {
@Test
void twoBindersOnTheClasspathAndNoDefault() {
try (Transcript t = new Transcript("08-two-binders-no-default")) {
t.line("$ both binder starters on the classpath, no spring.cloud.stream.default-binder, no per-binding binder");
String message;
try (ConfigurableApplicationContext ctx = new SpringApplicationBuilder(CloudStreamApplication.class)
.web(WebApplicationType.NONE).run("--spring.cloud.function.definition=priceOrder")) {
message = "context started";
} catch (Exception e) {
Throwable root = e;
while (root.getCause() != null && !root.getMessage().contains("more than one binder")) {
root = root.getCause();
}
message = root.getClass().getSimpleName() + ": " + root.getMessage();
}
t.line("%s", message);
assertThat(message).contains("more than one binder");
}
}
@Test
void definitionMissing() {
try (Transcript t = new Transcript("09-no-function-definition");
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(
TestChannelBinderConfiguration.getCompleteConfiguration(CloudStreamApplication.class))
.web(WebApplicationType.NONE).run("--spring.cloud.function.definition=", "--demo.max-orders=3")) {
t.line("$ three function beans (orderSource, priceOrder, bill), spring.cloud.function.definition left empty");
t.line("beans of type Function: %s, Supplier: %s, Consumer: %s",
new java.util.TreeSet<>(java.util.Arrays.asList(ctx.getBeanNamesForType(java.util.function.Function.class))),
new java.util.TreeSet<>(java.util.Arrays.asList(ctx.getBeanNamesForType(java.util.function.Supplier.class))),
new java.util.TreeSet<>(java.util.Arrays.asList(ctx.getBeanNamesForType(java.util.function.Consumer.class))));
InputDestination in = ctx.getBean(InputDestination.class);
OutputDestination out = ctx.getBean(OutputDestination.class);
String result;
try {
in.send(MessageBuilder.withPayload("{\"orderId\":\"o-1\",\"customerId\":\"alice\",\"quantity\":2,\"unitPrice\":9.5}".getBytes()).build(), "orders");
Message<byte[]> reply = out.receive(1500, "invoices");
result = reply == null ? "sent to 'orders', nothing came out of 'invoices'" : "reply: " + new String(reply.getPayload());
} catch (Exception e) {
result = "send threw " + e.getClass().getSimpleName() + ": " + e.getMessage();
}
t.line("%s", result);
}
}
@Test
void requiredGroupsWithoutProducerDlqArguments(CapturedOutput output) throws Exception {
try (Transcript t = new Transcript("10-rabbit-required-groups-mismatch");
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(CloudStreamApplication.class)
.web(WebApplicationType.NONE)
.run(Brokers.concat(new String[] {"--spring.profiles.active=rabbit", "--demo.max-orders=3",
"--spring.cloud.function.definition=priceOrder;bill",
"--spring.cloud.stream.rabbit.bindings.priceOrder-out-0.producer.auto-bind-dlq=false"},
Test02KafkaPipelineTest.prefixed(Brokers.rabbitProps()),
Test02KafkaPipelineTest.prefixed(Brokers.suffixed("r6"))))) {
t.line("$ rabbit profile, but the producer binding priceOrder-out-0 has required-groups=billing and auto-bind-dlq=false");
assertThat(Await.until(Duration.ofSeconds(20), () -> output.getAll().contains("PRECONDITION_FAILED"))).isTrue();
String line = output.getAll().lines().filter(l -> l.contains("PRECONDITION_FAILED")).findFirst().get();
t.line("%s", line.substring(line.indexOf("reply-code=")).replaceAll("class-id.*", "").replace("invoices-r6", "invoices-<run>").replaceAll(",\\s*$", ""));
}
}
}
@@ -0,0 +1,36 @@
package com.ankurm.cloudstream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Collects lines and writes them to output/NN-name.txt when closed. Tests assert the same values
* they print, so every number in the article is an assertion that fails the build when it stops being true.
*/
public final class Transcript implements AutoCloseable {
private final Path file;
private final List<String> lines = new ArrayList<>();
public Transcript(String name) {
this.file = Path.of(System.getProperty("user.dir"), "output", name + ".txt");
}
public Transcript line(String format, Object... args) {
lines.add(args.length == 0 ? format : String.format(format, args));
return this;
}
@Override
public void close() {
try {
Files.createDirectories(file.getParent());
Files.write(file, lines);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}