Compare commits

..
1 Commits
Author SHA1 Message Date
asmhatre 00910f2291 Add the protocol-comparison module 2026-09-04 00:52:18 +05:30
226 changed files with 40 additions and 6925 deletions
+3 -10
View File
@@ -1,10 +1,9 @@
# spring-messaging-demo # spring-messaging-demo
Companion code for the messaging series on [ankurm.com](https://ankurm.com). Each directory is a Companion code for the messaging series on [ankurm.com](https://ankurm.com). Each directory is a
self-contained Maven project for one article, with its own `pom.xml` and its own captured self-contained Maven project for one article, with its own `pom.xml`, its own numbered
output, regenerated from the test suite rather than typed by hand. Most modules keep that documentation chapters, and its own captured output under `docs/output/` — regenerated by that
output under `docs/output/` alongside numbered documentation chapters; `saga/` and `share-groups/` keep it module's `scripts/run-all.sh`, never typed by hand.
directly under `output/` instead, with the equivalent depth in the article's own accordion sections.
| Module | Article | What it demonstrates | | Module | Article | What it demonstrates |
|---|---|---| |---|---|---|
@@ -14,12 +13,6 @@ directly under `output/` instead, with the equivalent depth in the article's own
| [`sse-websocket/`](sse-websocket/README.md) | [Server-Sent Events and WebSocket on Spring Boot 4: SseEmitter, STOMP, and Which to Pick](https://ankurm.com/spring-boot-4-sse-websocket-stomp/) | The two browser-facing options side by side: the SSE lifecycle and the three ways a stream ends, STOMP's routing defaults, and the size limit that is enforced by Tomcat rather than by Spring | | [`sse-websocket/`](sse-websocket/README.md) | [Server-Sent Events and WebSocket on Spring Boot 4: SseEmitter, STOMP, and Which to Pick](https://ankurm.com/spring-boot-4-sse-websocket-stomp/) | The two browser-facing options side by side: the SSE lifecycle and the three ways a stream ends, STOMP's routing defaults, and the size limit that is enforced by Tomcat rather than by Spring |
| [`protocol-comparison/`](protocol-comparison/README.md) | [RSocket vs gRPC vs WebSocket on Spring Boot 4.1: When Each One Wins](https://ankurm.com/rsocket-vs-grpc-vs-websocket-spring-boot-4-1/) | One application serving the same two operations over all three, benchmarked in one JVM, ending in the only measurement that transfers off the box: what each server produces for a consumer that asked for a hundred | | [`protocol-comparison/`](protocol-comparison/README.md) | [RSocket vs gRPC vs WebSocket on Spring Boot 4.1: When Each One Wins](https://ankurm.com/rsocket-vs-grpc-vs-websocket-spring-boot-4-1/) | One application serving the same two operations over all three, benchmarked in one JVM, ending in the only measurement that transfers off the box: what each server produces for a consumer that asked for a hundred |
| [`broker-comparison/`](broker-comparison/README.md) | [Kafka vs RabbitMQ vs Pulsar for Java Teams: A Decision Framework with Benchmarks](https://ankurm.com/kafka-vs-rabbitmq-vs-pulsar-java-decision-framework/) | The three brokers measured side by side on ordering, replay, consumer scaling and operational footprint, ending in a decision table where every row has a transcript behind it | | [`broker-comparison/`](broker-comparison/README.md) | [Kafka vs RabbitMQ vs Pulsar for Java Teams: A Decision Framework with Benchmarks](https://ankurm.com/kafka-vs-rabbitmq-vs-pulsar-java-decision-framework/) | The three brokers measured side by side on ordering, replay, consumer scaling and operational footprint, ending in a decision table where every row has a transcript behind it |
| [`saga/`](saga/README.md) | Saga Pattern in Spring Boot: Orchestration vs Choreography with Kafka | The same order/payment/inventory saga built twice against a real broker — choreography and orchestration — driven through the same inventory failure so the compensating transaction can be compared side by side, plus a real duplicate-delivery test for the idempotent-consumer problem |
| [`share-groups/`](share-groups/README.md) | [Queues for Kafka: Share Groups with Spring for Apache Kafka 4](https://ankurm.com/kafka-share-groups-spring-kafka-4-queues-for-kafka/) | Share groups against a real Kafka 4.3.1 broker: six consumers on two partitions, the acquire mode that decides whether they really share, the three acknowledgement types, a group that starts at the end of the topic, and the ordering you give up |
| [`kafka-streams/`](kafka-streams/README.md) | Kafka Streams with Spring Boot 4: Real-Time Fraud Detection with Vector Similarity | A fraud topology tested entirely under `TopologyTestDriver`: cosine-similarity scoring, a 5-minute windowed count that alerts exactly once, and a KTable blocklist join with a tombstone, plus the Spring wiring that needs no broker to load |
| [`amqp10/`](amqp10/README.md) | AMQP 1.0 in Spring Boot 4.2 with RabbitMQ 4 | The generic AMQP 1.0 starter and RabbitMQ's own AMQP 1.0 client against a real RabbitMQ 4.4 broker: address forms and what a broker refusal looks like, a queue shared with AMQP 0-9-1, and a listener that kills its own consumer under Boot's defaults. Needs Docker (Testcontainers). Output lives in `output/`, no `docs/` folder |
| [`cloud-stream/`](cloud-stream/README.md) | Spring Cloud Stream on Boot 4: Functional Kafka and RabbitMQ Binders | One set of `Supplier`/`Function`/`Consumer` beans on Kafka and on RabbitMQ: partitioning (and how each binder really does it), dead-letter queues, the test binder, and the wiring mistakes with their real error messages. Needs Docker (Testcontainers). Output lives in `output/`, no `docs/` folder |
| [`debezium-cdc/`](debezium-cdc/README.md) | Debezium CDC with Spring Boot: Stream Postgres Changes to Kafka (and When to Prefer the Outbox) | Debezium 3.7.1 against Postgres 18 and Kafka 4.4, run two ways: Kafka Connect and the embedded engine inside a Spring Boot 4.2 app. Event envelope and replica identity, per-key ordering, redelivery after `kill -9`, WAL pinned by a quiet or orphaned slot, and the outbox `EventRouter`. Needs Docker. Output lives in `output/`, no `docs/` folder |
The brokers make an instructive set. Kafka's consumer holds an offset and the broker remembers The brokers make an instructive set. Kafka's consumer holds an offset and the broker remembers
nothing about individual records; RabbitMQ's broker owns the message until it is acknowledged and nothing about individual records; RabbitMQ's broker owns the message until it is acknowledged and
-47
View File
@@ -1,47 +0,0 @@
# amqp10 — AMQP 1.0 in Spring Boot 4.2 with RabbitMQ 4
Companion code for the ankurm.com article *AMQP 1.0 in Spring Boot 4.2 with RabbitMQ 4*. Every
number in the article comes from a file in [`output/`](output), written by the test suite against a
real RabbitMQ broker started by Testcontainers.
| Piece | Version | Where it was read from |
|---|---|---|
| Spring Boot | 4.2.0 (GA 19 Nov 2026) | `maven-metadata.xml` |
| Spring Framework / Spring AMQP | 7.1.0 / 4.2.0 | Boot's dependency management |
| protonj2-client (generic AMQP 1.0) | 1.4.0 | `spring-boot-amqp` 4.2.0 pom |
| RabbitMQ AMQP 1.0 client | `com.rabbitmq.client:amqp-client` 1.7.0, via `spring-boot-starter-amqp-rabbitmq` 4.2.0 | resolved dependency tree |
| Broker | RabbitMQ 4.4.1 on Erlang 29.1.3 | `rabbitmq:4-management`, see `output/01-broker.txt` |
| JDK | Temurin 25.0.5.1 | |
| Testcontainers | 2.0.5 (`testcontainers-rabbitmq`) | Boot's BOM |
Boot 4.2 has three AMQP starters: `spring-boot-starter-amqp` (generic AMQP 1.0), `spring-boot-starter-amqp-rabbitmq`
(RabbitMQ's own AMQP 1.0 client) and `spring-boot-starter-rabbitmq` (classic AMQP 0-9-1). This module uses the first
two and talks to the third with a plain `RabbitTemplate` in the interop test.
## Run it
```bash
export JAVA_HOME=/path/to/jdk-25
./scripts/run-all.sh # needs Docker: Testcontainers starts rabbitmq:4-management
```
## What the tests show
| Test | Transcript | What it demonstrates |
|---|---|---|
| `Test01BrokerTest` | `01-broker.txt` | Broker version, enabled plugins: AMQP 1.0 needs no plugin on 4.x |
| `Test02GenericTest` | `02-generic-send-receive.txt`, `03-generic-pull-and-peek.txt` | `spring-boot-starter-amqp`: `AmqpClient` + `@AmqpListener`, how a message looks to the broker, and the untyped-pull trap that loses a message |
| `Test04AddressFailuresTest` | `04-address-failures.txt` | Which address forms work and what RELEASED / REJECTED mean |
| `Test05CredentialsTest` | `05-connection-mistakes.txt` | No credentials, wrong password, wrong port |
| `Test06RabbitClientTest` | `06-rabbit-client.txt` | `spring-boot-starter-amqp-rabbitmq`: auto-configured beans, declared topology, publish with confirms, `@RabbitListener` |
| `Test07InteropTest` | `07-classic-interop.txt` | One queue written by AMQP 0-9-1 and read by AMQP 1.0, and back |
| `Test08PoisonTest` | `08-poison-default.txt` | A throwing `@AmqpListener` kills its consumer under Boot's defaults |
| `Test09HandledTest` | `09-poison-with-error-handler.txt` | The same listeners with a container `ErrorHandler` |
| `scripts/compare-starters.sh` | `10-starter-comparison.txt` | What the two Boot starters contain, read from their jars |
Main sources: [`GenericOrderListener`](src/main/java/com/ankurm/amqp10/GenericOrderListener.java),
[`RabbitSpecificConfig`](src/main/java/com/ankurm/amqp10/RabbitSpecificConfig.java),
[`PoisonListeners`](src/main/java/com/ankurm/amqp10/PoisonListeners.java),
[`HandledFactoryConfig`](src/main/java/com/ankurm/amqp10/HandledFactoryConfig.java).
There is no `docs/` folder: the explanations live in the article's own collapsible sections.
-12
View File
@@ -1,12 +0,0 @@
$ docker image: rabbitmq:4-management
rabbitmq_version = 4.4.1
erlang_version = 29.1.3
$ rabbitmq-plugins list -E -m
Listing plugins with pattern ".*" ...
rabbitmq_management
rabbitmq_prometheus
listeners:
amqp on port 5672
clustering on port 25672
http on port 15672
http/prometheus on port 15692
@@ -1,9 +0,0 @@
$ AmqpClient.to("/queues/orders.generic").body(order).send()
send o-1 -> accepted=true
send o-2 -> accepted=true
send o-3 -> accepted=true
@AmqpListener received 3: [o-1, o-2, o-3]
queue orders.generic: type=quorum consumers=1 messages=0
$ rabbitmqctl list_connections protocol user
protocol user
{1, 0} guest
@@ -1,11 +0,0 @@
what the broker holds (management API, 0-9-1 view of an AMQP 1.0 message):
payload = {"id":"p-1","item":"mouse","qty":3}
content_type = application/json
headers = {"__TypeId__":"com.ankurm.amqp10.OrderMessage"}
depth before pulling = 2
$ untyped: Object o = from("/queues/orders.pull").receiveAndConvert().get()
-> java.lang.IllegalArgumentException: The class 'com.ankurm.amqp10.OrderMessage' is not in the trusted packages: [java.util, jav...
depth after the failed conversion = 1
$ typed: CompletableFuture<OrderMessage> f = from(...).receiveAndConvert()
-> OrderMessage[id=p-2, item=dock, qty=1]
depth after the typed pull = 0
-10
View File
@@ -1,10 +0,0 @@
to("/queues/orders.generic")
returned true after 13 ms
to("/queues/does.not.exist")
threw AmqpClientNackReceivedException: The message was not accepted, but RELEASED after 5 ms
to("orders.generic")
threw AmqpClientNackReceivedException: The message was not accepted, but REJECTED after 5 ms
to("/queue/orders.generic")
threw AmqpClientNackReceivedException: The message was not accepted, but REJECTED after 2 ms
to("/exchanges/amq.direct/nobody-listens")
threw AmqpClientNackReceivedException: The message was not accepted, but RELEASED after 2 ms
-12
View File
@@ -1,12 +0,0 @@
no spring.amqp.username / password set:
context started = true
send -> true (context up in 953 ms); broker sees: {1, 0} guest
username=guest password=wrong:
context started = false
javax.security.sasl.AuthenticationException: SASL exchange failed to authenticate client (3271 ms)
username=guest password=guest:
context started = true
send -> true (context up in 988 ms); broker sees: {1, 0} guest
port=1 (nothing listens):
context started = false
java.net.ConnectException: finishConnect(..) failed with error(-111): Connection refused (202 ms)
-14
View File
@@ -1,14 +0,0 @@
beans from spring-boot-starter-amqp-rabbitmq (no @Bean written for them):
RabbitAmqpTemplate [rabbitAmqpTemplate]
RabbitAmqpAdmin [rabbitAmqpAdmin]
RabbitAmqpListenerContainerFactory [rabbitListenerContainerFactory]
AmqpConnectionFactory [amqpRabbitConnectionFactory]
declared by RabbitAmqpAdmin:
queue orders.rabbit type=quorum durable=true
exchange orders.topic type=topic
binding orders.topic -> orders.rabbit key=orders.created
$ template.convertAndSend("orders.topic", "orders.created", order).get() -> true
@RabbitListener(queues = "orders.rabbit") received OrderMessage[id=r-1, item=router, qty=2]
unroutable key : threw AmqpNackReceivedException: The message was rejected after 4 ms
missing exchange: threw AmqpMessageRejectedException: no exchange 'no.such.exchange' in vhost '/' after 2 ms
$ rabbitmqctl list_connections protocol -> an AMQP 1.0 connection is open: true
-16
View File
@@ -1,16 +0,0 @@
0-9-1 producer (RabbitTemplate) -> AMQP 1.0 consumer (AmqpClient.receive):
body = {"id":"i-1","item":"classic","qty":1}
messageId = m-classic
correlationId = c-classic
contentType = application/json
deliveryMode = null
headers = {attempt=3, tenant=acme}
AMQP 1.0 producer (AmqpClient.to) -> 0-9-1 consumer (RabbitTemplate.receive):
body = {"id":"i-2","item":"amqp10","qty":2}
messageId = m-amqp10
correlationId = c-amqp10
contentType = application/json
deliveryMode = PERSISTENT
headers = {__TypeId__=com.ankurm.amqp10.OrderMessage, attempt=3, tenant=acme}
$ rabbitmqctl list_connections protocol, while both clients are connected:
AMQP 0-9-1 connection open = true, AMQP 1.0 connection open = true
-7
View File
@@ -1,7 +0,0 @@
container errorHandler (Boot's default factory) = null
one bad message sent to each queue, listener always throws:
listener attempts consumers messages left in queue
plain exception, autoAccept default 1 0 1 (the bad message was lost; the follow-up is waiting)
AmqpRejectAndDontRequeueException 1 0 0
plain exception, autoAccept=false 1 0 1 (released back, but nobody is left to take it)
follow-up message good-1 delivered to the plain listener? attempts still = 1
@@ -1,6 +0,0 @@
container errorHandler = set (lambda)
with a container ErrorHandler (HandledFactoryConfig), one bad message per queue:
plain exception, autoAccept default : 1 attempt(s); follow-up good-1 reached the listener = true
AmqpRejectAndDontRequeueException : 1 attempt(s)
plain exception, autoAccept=false : 1877 attempts in 3 seconds (figure varies per run, still counting)
queue orders.poison.manual depth now : 2
-57
View File
@@ -1,57 +0,0 @@
Spring Boot 4.2.0
== spring-boot-starter-amqp: description and dependencies
<description>Starter for generic AMQP 1.0 support</description>
<artifactId>spring-boot-amqp</artifactId>
== spring-boot-starter-amqp-rabbitmq: description and dependencies
<description>Starter for using Spring AMQP with Rabbit MQ over AMQP 1.0 protocol</description>
<artifactId>spring-boot-amqp-rabbitmq</artifactId>
== spring-boot-starter-rabbitmq: description and dependencies
<description>Starter for using RabbitMQ messaging and streaming broker</description>
<artifactId>spring-boot-rabbitmq</artifactId>
== spring-boot-amqp auto-configuration classes
org.springframework.boot.amqp.autoconfigure.AmqpAutoConfiguration
== spring-boot-amqp properties (spring.amqp.*)
spring.amqp.client.completion-timeout default=60s
spring.amqp.client.default-to-address default=None
spring.amqp.host default=localhost
spring.amqp.listener.auto-startup default=True
spring.amqp.listener.concurrency default=1
spring.amqp.listener.default-requeue-rejected default=True
spring.amqp.listener.graceful-shutdown-period default=30s
spring.amqp.listener.initial-credits default=100
spring.amqp.listener.receive-timeout default=1s
spring.amqp.password default=None
spring.amqp.port default=5672
spring.amqp.username default=None
== spring-boot-amqp-rabbitmq auto-configuration classes
org.springframework.boot.amqp.rabbitmq.autoconfigure.AmqpRabbitAutoConfiguration
org.springframework.boot.amqp.rabbitmq.autoconfigure.health.AmqpRabbitHealthContributorAutoConfiguration
== spring-boot-amqp-rabbitmq properties (spring.amqp.rabbitmq.*)
spring.amqp.rabbitmq.address default=None
spring.amqp.rabbitmq.host default=localhost
spring.amqp.rabbitmq.password default=None
spring.amqp.rabbitmq.port default=None
spring.amqp.rabbitmq.username default=None
== spring-boot-rabbitmq auto-configuration classes
org.springframework.boot.rabbitmq.autoconfigure.RabbitAutoConfiguration
org.springframework.boot.rabbitmq.autoconfigure.health.RabbitHealthContributorAutoConfiguration
org.springframework.boot.rabbitmq.autoconfigure.metrics.RabbitMetricsAutoConfiguration
== spring-boot-rabbitmq properties (selected spring.rabbitmq.*)
spring.rabbitmq.host default=localhost
spring.rabbitmq.password default=guest
spring.rabbitmq.port default=None
spring.rabbitmq.username default=guest
spring.rabbitmq.virtual-host default=None
== which Boot module wires RabbitMQ's AMQP 1.0 client (RabbitAmqpTemplate)?
spring-boot-amqp: auto-configuration classes mentioning RabbitAmqpTemplate: no
spring-boot-amqp-rabbitmq: auto-configuration classes mentioning RabbitAmqpTemplate: yes
spring-boot-rabbitmq: auto-configuration classes mentioning RabbitAmqpTemplate: no
-65
View File
@@ -1,65 +0,0 @@
<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>amqp10-spring-boot</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<java.version>25</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- In Boot 4.2 this starter means GENERIC AMQP 1.0 (protonj2 + spring-amqp-client, properties
under spring.amqp.*). The classic RabbitMQ 0-9-1 starter is spring-boot-starter-rabbitmq. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- The third Boot 4.2 AMQP starter: RabbitMQ's own AMQP 1.0 client (spring-rabbitmq-client),
properties under spring.amqp.rabbitmq.*. It auto-configures RabbitAmqpTemplate, RabbitAmqpAdmin
and a RabbitAmqpListenerContainerFactory; the classic 0-9-1 starter is spring-boot-starter-rabbitmq. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp-rabbitmq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-rabbitmq</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
-54
View File
@@ -1,54 +0,0 @@
#!/usr/bin/env bash
# Prints what the two Boot 4.2.0 starters really contain, read straight from their jars
# (spring-configuration-metadata.json and the auto-configuration imports). Run after one mvn build
# so the jars are in ~/.m2.
set -eu
cd "$(dirname "$0")/.."
OUT=output/10-starter-comparison.txt
M2="${HOME}/.m2/repository"
BOOT=$(ls "$M2/org/springframework/boot/spring-boot-amqp" | sort -V | tail -1)
fetch() { # fetch <group-path> <artifact> <version> -> jar path (downloads via maven if missing)
local jar="$M2/$1/$2/$3/$2-$3.jar"
[ -f "$jar" ] || mvn -B -q dependency:get -Dartifact="$(echo "$1" | tr / .):$2:$3" >/dev/null
echo "$jar"
}
props() { # props <jar> <prefix-filter>
unzip -p "$1" META-INF/spring-configuration-metadata.json | python3 -c "
import json,sys
d=json.load(sys.stdin)
for p in d['properties']:
if p['name'].startswith('$2'):
print(' %-48s default=%s' % (p['name'], p.get('defaultValue')))"
}
{
echo "Spring Boot $BOOT"
for s in amqp amqp-rabbitmq rabbitmq; do
echo
echo "== spring-boot-starter-$s: description and dependencies"
pom="$M2/org/springframework/boot/spring-boot-starter-$s/$BOOT/spring-boot-starter-$s-$BOOT.pom"
[ -f "$pom" ] || mvn -B -q dependency:get -Dartifact="org.springframework.boot:spring-boot-starter-$s:$BOOT:pom" >/dev/null
grep -E '<description>|<artifactId>spring-boot-(amqp|amqp-rabbitmq|rabbitmq)<' "$pom" | sed 's/^ *//'
done
echo
echo "== spring-boot-amqp auto-configuration classes"
unzip -p "$(fetch org/springframework/boot spring-boot-amqp "$BOOT")" META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports | sed 's/^/ /'; echo
echo "== spring-boot-amqp properties (spring.amqp.*)"
props "$(fetch org/springframework/boot spring-boot-amqp "$BOOT")" spring.amqp.
echo
echo "== spring-boot-amqp-rabbitmq auto-configuration classes"
unzip -p "$(fetch org/springframework/boot spring-boot-amqp-rabbitmq "$BOOT")" META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports | sed 's/^/ /'; echo
echo "== spring-boot-amqp-rabbitmq properties (spring.amqp.rabbitmq.*)"
props "$(fetch org/springframework/boot spring-boot-amqp-rabbitmq "$BOOT")" spring.amqp.rabbitmq. | grep -E 'rabbitmq\.(host|port|username|password|address) '
echo
echo "== spring-boot-rabbitmq auto-configuration classes"
unzip -p "$(fetch org/springframework/boot spring-boot-rabbitmq "$BOOT")" META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports | sed 's/^/ /'; echo
echo "== spring-boot-rabbitmq properties (selected spring.rabbitmq.*)"
props "$(fetch org/springframework/boot spring-boot-rabbitmq "$BOOT")" spring.rabbitmq. | grep -E 'rabbitmq\.(host|port|username|password|virtual-host) '
echo
echo "== which Boot module wires RabbitMQ's AMQP 1.0 client (RabbitAmqpTemplate)?"
for j in spring-boot-amqp spring-boot-amqp-rabbitmq spring-boot-rabbitmq; do
n=$(unzip -p "$(fetch org/springframework/boot $j "$BOOT")" 'org/springframework/boot/*/autoconfigure/*AutoConfiguration*.class' 2>/dev/null | strings | grep -c 'RabbitAmqpTemplate' || true)
echo " $j: auto-configuration classes mentioning RabbitAmqpTemplate: $([ "$n" -gt 0 ] && echo yes || echo no)"
done
} > "$OUT"
cat "$OUT"
-10
View File
@@ -1,10 +0,0 @@
#!/usr/bin/env bash
# Regenerates every file under output/ : the tests write output/01..09, the script writes output/10.
# Needs JDK 25, Maven and a running Docker daemon (Testcontainers starts rabbitmq:4-management).
set -eu
cd "$(dirname "$0")/.."
mkdir -p output
# Overwritten, not deleted, by the tests.
mvn -B -q test
./scripts/compare-starters.sh > /dev/null
ls -1 output
@@ -1,11 +0,0 @@
package com.ankurm.amqp10;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Amqp10Application {
public static void main(String[] args) {
SpringApplication.run(Amqp10Application.class, args);
}
}
@@ -1,27 +0,0 @@
package com.ankurm.amqp10;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.amqp.client.annotation.AmqpListener;
import org.springframework.stereotype.Component;
/**
* Receives with the GENERIC AMQP 1.0 client. {@code @AmqpListener} takes an AMQP 1.0 address, not a
* queue name: {@code /queues/<name>} is RabbitMQ's "address v2" form for a queue. The queue must
* already exist, because the generic client has no way to declare anything.
*/
@Component
public class GenericOrderListener {
private final List<OrderMessage> received = new CopyOnWriteArrayList<>();
@AmqpListener(id = "generic-orders", addresses = "/queues/orders.generic")
void onOrder(OrderMessage order) {
received.add(order);
}
public List<OrderMessage> received() {
return received;
}
}
@@ -1,33 +0,0 @@
package com.ankurm.amqp10;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.client.AmqpConnectionFactory;
import org.springframework.amqp.client.config.MethodAmqpMessageListenerContainerFactory;
import org.springframework.boot.amqp.autoconfigure.AmqpMessageListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* Replaces Boot's listener container factory with one that has a container-level ErrorHandler.
* Boot's own factory has none, and the container treats "no error handler" as "stop this consumer".
* The bean name matters: @AmqpListener looks up "amqpListenerContainerFactory" by default, which is
* the name Boot registers (its Java method is called amqpMessageListenerContainerFactory, so naming
* ours after the method silently leaves Boot's factory in charge).
*/
@Configuration(proxyBeanMethods = false)
@Profile("handled")
public class HandledFactoryConfig {
private static final Log LOG = LogFactory.getLog(HandledFactoryConfig.class);
@Bean
MethodAmqpMessageListenerContainerFactory amqpListenerContainerFactory(
AmqpMessageListenerContainerFactoryConfigurer configurer, AmqpConnectionFactory connectionFactory) {
MethodAmqpMessageListenerContainerFactory factory = new MethodAmqpMessageListenerContainerFactory(connectionFactory);
configurer.configure(factory); // keep every spring.amqp.listener.* property Boot would have applied
factory.setErrorHandler(t -> LOG.warn("listener failed, consumer stays alive: " + t.getMessage()));
return factory;
}
}
@@ -1,5 +0,0 @@
package com.ankurm.amqp10;
/** The payload every demo sends. A record, serialised as JSON by the auto-configured converter. */
public record OrderMessage(String id, String item, int qty) {
}
@@ -1,54 +0,0 @@
package com.ankurm.amqp10;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.client.annotation.AmqpListener;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
* Two listeners that always fail, to show what the default failure handling does with a message
* the code can never process. Only active under the "poison" profile.
*/
@Component
@Profile("poison")
public class PoisonListeners {
private final AtomicInteger plainAttempts = new AtomicInteger();
private final AtomicInteger rejectAttempts = new AtomicInteger();
private final AtomicInteger manualAttempts = new AtomicInteger();
/** A plain exception: the container's default is to requeue the message. */
@AmqpListener(id = "poison-plain", addresses = "/queues/orders.poison.plain")
void plain(OrderMessage order) {
plainAttempts.incrementAndGet();
throw new IllegalStateException("cannot process " + order.id());
}
/** The same failure, but the listener says do not requeue. */
@AmqpListener(id = "poison-reject", addresses = "/queues/orders.poison.reject")
void reject(OrderMessage order) {
rejectAttempts.incrementAndGet();
throw new AmqpRejectAndDontRequeueException("cannot process " + order.id());
}
/** Same failure with autoAccept switched off: the container, not the broker, decides the outcome. */
@AmqpListener(id = "poison-manual", addresses = "/queues/orders.poison.manual", autoAccept = "false")
void manual(OrderMessage order) {
manualAttempts.incrementAndGet();
throw new IllegalStateException("cannot process " + order.id());
}
public int manualAttempts() {
return manualAttempts.get();
}
public int plainAttempts() {
return plainAttempts.get();
}
public int rejectAttempts() {
return rejectAttempts.get();
}
}
@@ -1,54 +0,0 @@
package com.ankurm.amqp10;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Declarables;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
* Everything the RabbitMQ AMQP 1.0 starter does not do for you: the topology (a quorum queue, a topic
* exchange and a binding) and one listener. The connection, RabbitAmqpTemplate, RabbitAmqpAdmin and the
* listener container factory all come from spring-boot-starter-amqp-rabbitmq's auto-configuration.
*/
@Configuration(proxyBeanMethods = false)
@Profile("rabbit")
public class RabbitSpecificConfig {
public static final String QUEUE = "orders.rabbit";
public static final String EXCHANGE = "orders.topic";
public static final String ROUTING_KEY = "orders.created";
/** Declared by RabbitAmqpAdmin when the context starts. */
@Bean
Declarables rabbitTopology() {
Queue queue = QueueBuilder.durable(QUEUE).quorum().build();
TopicExchange exchange = new TopicExchange(EXCHANGE);
Binding binding = BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY);
return new Declarables(queue, exchange, binding);
}
@Component
@Profile("rabbit")
public static class RabbitOrderListener {
private final List<OrderMessage> received = new CopyOnWriteArrayList<>();
@RabbitListener(queues = QUEUE)
void onOrder(OrderMessage order) {
received.add(order);
}
public List<OrderMessage> received() {
return received;
}
}
}
@@ -1,6 +0,0 @@
# Generic AMQP 1.0 starter (spring-boot-starter-amqp) uses the spring.amqp.* prefix.
# Host/port/credentials come from the Testcontainers connection details in tests.
spring.application.name=amqp10
spring.amqp.client.completion-timeout=10s
logging.level.root=WARN
logging.level.com.ankurm=INFO
@@ -1,25 +0,0 @@
package com.ankurm.amqp10;
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();
}
}
@@ -1,140 +0,0 @@
package com.ankurm.amqp10;
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.rabbitmq.RabbitMQContainer;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* One real RabbitMQ 4 broker for the whole test run, plus a tiny management-API client. The
* generic AMQP 1.0 client cannot declare queues, so tests declare them here over HTTP.
*/
public final class Broker {
public static final String IMAGE = "rabbitmq:4-management";
public static final RabbitMQContainer CONTAINER = new RabbitMQContainer(IMAGE);
private static final JsonMapper JSON = JsonMapper.builder().build();
private static final HttpClient HTTP = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
static {
CONTAINER.start();
declareQueue("orders.generic", "quorum");
declareQueue("orders.pull", "quorum");
declareQueue("orders.interop", "classic");
declareQueue("orders.poison.plain", "quorum");
declareQueue("orders.poison.reject", "quorum");
declareQueue("orders.poison.manual", "quorum");
}
private Broker() {
}
private static String mgmt(String path) {
return "http://" + CONTAINER.getHost() + ":" + CONTAINER.getMappedPort(15672) + "/api" + path;
}
private static HttpRequest.Builder request(String path) {
String auth = Base64.getEncoder().encodeToString(
(CONTAINER.getAdminUsername() + ":" + CONTAINER.getAdminPassword()).getBytes());
return HttpRequest.newBuilder(URI.create(mgmt(path))).header("Authorization", "Basic " + auth)
.header("Content-Type", "application/json");
}
public static JsonNode get(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 post(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);
}
}
public static void declareQueue(String name, String type) {
try {
String body = "{\"durable\":true,\"arguments\":{\"x-queue-type\":\"" + type + "\"}}";
int status = HTTP.send(request("/queues/%2F/" + name).PUT(HttpRequest.BodyPublishers.ofString(body)).build(),
HttpResponse.BodyHandlers.ofString()).statusCode();
if (status != 201 && status != 204) {
throw new IllegalStateException("declare " + name + " -> HTTP " + status);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
/** Run rabbitmqctl inside the container: unlike the management API its numbers are not sampled. */
public static String ctl(String... args) {
try {
String[] cmd = new String[args.length + 2];
cmd[0] = "rabbitmqctl";
cmd[1] = "-q";
System.arraycopy(args, 0, cmd, 2, args.length);
return CONTAINER.execInContainer(cmd).getStdout();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
/** Messages ready + unacked as rabbitmqctl reports them. Both rabbitmqctl and the management API sample queue metrics on a timer (5 s), so use awaitDepth after a change. */
public static int depth(String queue) {
for (String line : ctl("list_queues", "name", "messages").split("\n")) {
String[] cols = line.split("\\s+");
if (cols.length == 2 && cols[0].equals(queue)) {
return Integer.parseInt(cols[1]);
}
}
return -1;
}
/** Consumer count as rabbitmqctl reports it (sampled, so poll it). */
public static int consumers(String queue) {
for (String line : ctl("list_queues", "name", "consumers").split("\n")) {
String[] cols = line.split("\\s+");
if (cols.length == 2 && cols[0].equals(queue)) {
return Integer.parseInt(cols[1]);
}
}
return -1;
}
/** Reads the private errorHandler field of a listener container, as a string ("null" when unset). */
public static String errorHandlerOf(Object container) {
try {
var f = container.getClass().getDeclaredField("errorHandler");
f.setAccessible(true);
Object h = f.get(container);
return h == null ? "null" : "set (" + (h.getClass().getName().contains("Lambda") ? "lambda" : h.getClass().getSimpleName()) + ")";
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
}
public static void purge(String queue) {
ctl("purge_queue", queue);
}
/** Waits (up to 15 s) for the broker's own queue counter to reach {@code expected}; returns the last value read. */
public static int awaitDepth(String queue, int expected) {
Await.until(java.time.Duration.ofSeconds(15), () -> depth(queue) == expected);
return depth(queue);
}
/** Peek at the head of a queue without consuming it. */
public static JsonNode peek(String queue, int count) {
return post("/queues/%2F/" + queue + "/get",
"{\"count\":" + count + ",\"ackmode\":\"ack_requeue_true\",\"encoding\":\"auto\"}");
}
}
@@ -1,30 +0,0 @@
package com.ankurm.amqp10;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import tools.jackson.databind.JsonNode;
class Test01BrokerTest {
@Test
void brokerFacts() throws Exception {
JsonNode overview = Broker.get("/overview");
String version = overview.path("rabbitmq_version").asString();
var plugins = Broker.CONTAINER.execInContainer("rabbitmq-plugins", "list", "-E", "-m");
try (Transcript t = new Transcript("01-broker")) {
t.line("$ docker image: %s", Broker.IMAGE);
t.line("rabbitmq_version = %s", version);
t.line("erlang_version = %s", overview.path("erlang_version").asString());
t.line("$ rabbitmq-plugins list -E -m");
plugins.getStdout().lines().forEach(l -> t.line("%s", l));
t.line("listeners:");
for (JsonNode l : overview.path("listeners")) {
t.line(" %s on port %d", l.path("protocol").asString(), l.path("port").asInt());
}
}
assertThat(version).startsWith("4.");
// AMQP 1.0 is not a plugin on 4.x: the enabled-plugins list holds only the management UI.
assertThat(plugins.getStdout()).doesNotContain("rabbitmq_amqp1_0");
}
}
@@ -1,105 +0,0 @@
package com.ankurm.amqp10;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.client.AmqpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import tools.jackson.databind.JsonNode;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@Import(TestBrokerConfig.class)
class Test02GenericTest {
@Autowired
AmqpClient amqpClient;
@Autowired
GenericOrderListener listener;
@Autowired
ApplicationContext context;
@Test
void sendAndListen() throws Exception {
List<OrderMessage> sent = List.of(new OrderMessage("o-1", "keyboard", 1),
new OrderMessage("o-2", "monitor", 2), new OrderMessage("o-3", "cable", 5));
try (Transcript t = new Transcript("02-generic-send-receive")) {
t.line("$ AmqpClient.to(\"/queues/orders.generic\").body(order).send()");
for (OrderMessage o : sent) {
Boolean accepted = amqpClient.to("/queues/orders.generic").body(o).send().get();
t.line("send %s -> accepted=%s", o.id(), accepted);
assertThat(accepted).isTrue();
}
assertThat(Await.until(Duration.ofSeconds(10), () -> listener.received().size() == 3)).isTrue();
t.line("@AmqpListener received %d: %s", listener.received().size(),
listener.received().stream().map(OrderMessage::id).toList());
assertThat(listener.received()).containsExactlyElementsOf(sent);
// Management statistics are sampled every 5 s, so wait for the consumer to show up.
assertThat(Await.until(Duration.ofSeconds(15),
() -> Broker.get("/queues/%2F/orders.generic").path("consumers").asInt() == 1)).isTrue();
JsonNode q = Broker.get("/queues/%2F/orders.generic");
t.line("queue orders.generic: type=%s consumers=%d messages=%d", q.path("type").asString(),
q.path("consumers").asInt(), q.path("messages").asInt());
assertThat(q.path("consumers").asInt()).isEqualTo(1);
String conns = Broker.ctl("list_connections", "protocol", "user");
t.line("$ rabbitmqctl list_connections protocol user");
conns.lines().distinct().forEach(l -> t.line(" %s", l));
assertThat(conns).contains("{1, 0}");
}
}
@Test
void pullAndPeek() throws Exception {
try (Transcript t = new Transcript("03-generic-pull-and-peek")) {
amqpClient.to("/queues/orders.pull").body(new OrderMessage("p-1", "mouse", 3)).send().get();
amqpClient.to("/queues/orders.pull").body(new OrderMessage("p-2", "dock", 1)).send().get();
JsonNode peek = Broker.peek("orders.pull", 1);
t.line("what the broker holds (management API, 0-9-1 view of an AMQP 1.0 message):");
t.line(" payload = %s", peek.get(0).path("payload").asString());
t.line(" content_type = %s", peek.get(0).path("properties").path("content_type").asString());
t.line(" headers = %s", peek.get(0).path("properties").path("headers").toString());
int before = Broker.awaitDepth("orders.pull", 2);
t.line("depth before pulling = %d", before);
assertThat(before).isEqualTo(2);
// Untyped: T is inferred as Object, so the converter trusts only the __TypeId__ header.
String failure = null;
try {
Object any = amqpClient.from("/queues/orders.pull").timeout(Duration.ofSeconds(5))
.receiveAndConvert().get();
t.line("untyped receiveAndConvert() returned %s", any);
} catch (Exception e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
failure = root.getClass().getName() + ": " + root.getMessage().substring(0, 90) + "...";
}
t.line("$ untyped: Object o = from(\"/queues/orders.pull\").receiveAndConvert().get()");
t.line(" -> %s", failure);
assertThat(failure).contains("not in the trusted packages");
int afterFail = Broker.awaitDepth("orders.pull", 1);
t.line("depth after the failed conversion = %d", afterFail);
assertThat(afterFail).isEqualTo(1);
// Typed: the assigned type becomes the conversion target, so the header is not consulted.
java.util.concurrent.CompletableFuture<OrderMessage> typed =
amqpClient.from("/queues/orders.pull").timeout(Duration.ofSeconds(5)).receiveAndConvert();
OrderMessage pulled = typed.get();
t.line("$ typed: CompletableFuture<OrderMessage> f = from(...).receiveAndConvert()");
t.line(" -> %s", pulled);
assertThat(pulled.id()).isEqualTo("p-2");
int afterTyped = Broker.awaitDepth("orders.pull", 0);
t.line("depth after the typed pull = %d", afterTyped);
assertThat(afterTyped).isZero();
}
}
}
@@ -1,63 +0,0 @@
package com.ankurm.amqp10;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.client.AmqpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
/** What the generic client does with addresses it cannot use. Every line is a real result. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE,
properties = "spring.amqp.client.completion-timeout=5s")
@Import(TestBrokerConfig.class)
class Test04AddressFailuresTest {
@Autowired
AmqpClient amqpClient;
private static String outcome(Supplier<Object> action) {
long start = System.nanoTime();
try {
Object result = action.get();
return "returned " + result + " after " + (System.nanoTime() - start) / 1_000_000 + " ms";
} catch (Throwable e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
String msg = String.valueOf(root.getMessage()).replace('\n', ' ');
return "threw " + root.getClass().getSimpleName() + ": " + (msg.length() > 110 ? msg.substring(0, 110) + "..." : msg)
+ " after " + (System.nanoTime() - start) / 1_000_000 + " ms";
}
}
private String send(String address) {
return outcome(() -> {
try {
return amqpClient.to(address).body(new OrderMessage("x", "probe", 1)).send().get();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
@Test
void addresses() {
try (Transcript t = new Transcript("04-address-failures")) {
String[] addresses = { "/queues/orders.generic", "/queues/does.not.exist", "orders.generic",
"/queue/orders.generic", "/exchanges/amq.direct/nobody-listens" };
for (String a : addresses) {
String r = send(a);
t.line("to(\"%s\")", a);
t.line(" %s", r);
}
// The one good address must still work, and the bad ones must not have created anything.
assertThat(send("/queues/orders.generic")).startsWith("returned true");
assertThat(send("/queues/does.not.exist")).doesNotStartWith("returned true");
}
}
}
@@ -1,81 +0,0 @@
package com.ankurm.amqp10;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.client.AmqpClient;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
/** Starts the real application with broken connection settings, to see what a misconfiguration looks like. */
class Test05CredentialsTest {
private record Result(boolean started, String detail) {
}
private Result start(String... props) {
List<String> all = new ArrayList<>(List.of(
"spring.amqp.host=" + Broker.CONTAINER.getHost(),
"spring.amqp.port=" + Broker.CONTAINER.getAmqpPort(),
"spring.amqp.client.completion-timeout=5s"));
all.addAll(List.of(props));
long start = System.nanoTime();
try (ConfigurableApplicationContext ctx = new SpringApplicationBuilder(Amqp10Application.class)
.web(WebApplicationType.NONE).properties(all.toArray(String[]::new)).run()) {
// The context is up. Does a send actually work?
String send;
try {
send = "send -> " + ctx.getBean(AmqpClient.class).to("/queues/orders.generic")
.body(new OrderMessage("c", "probe", 1)).send().get();
} catch (Exception e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
send = "send threw " + root.getClass().getSimpleName() + ": " + root.getMessage();
}
String users = Broker.ctl("list_connections", "protocol", "user").lines().skip(1)
.map(String::strip).distinct().collect(java.util.stream.Collectors.joining(" | "));
return new Result(true, send + " (context up in " + (System.nanoTime() - start) / 1_000_000
+ " ms); broker sees: " + users);
} catch (Throwable e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
String msg = String.valueOf(root.getMessage()).replace('\n', ' ');
return new Result(false, root.getClass().getName() + ": " + (msg.length() > 140 ? msg.substring(0, 140) + "..." : msg)
+ " (" + (System.nanoTime() - start) / 1_000_000 + " ms)");
}
}
@Test
void connectionMistakes() {
try (Transcript t = new Transcript("05-connection-mistakes")) {
Result noCreds = start();
t.line("no spring.amqp.username / password set:");
t.line(" context started = %s", noCreds.started());
t.line(" %s", noCreds.detail());
Result wrongPassword = start("spring.amqp.username=guest", "spring.amqp.password=wrong");
t.line("username=guest password=wrong:");
t.line(" context started = %s", wrongPassword.started());
t.line(" %s", wrongPassword.detail());
Result right = start("spring.amqp.username=guest", "spring.amqp.password=guest");
t.line("username=guest password=guest:");
t.line(" context started = %s", right.started());
t.line(" %s", right.detail());
assertThat(right.started()).isTrue();
Result wrongPort = start("spring.amqp.username=guest", "spring.amqp.password=guest", "spring.amqp.port=1");
t.line("port=1 (nothing listens):");
t.line(" context started = %s", wrongPort.started());
t.line(" %s", wrongPort.detail());
}
}
}
@@ -1,95 +0,0 @@
package com.ankurm.amqp10;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbitmq.client.RabbitAmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ActiveProfiles;
import tools.jackson.databind.JsonNode;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@Import(TestBrokerConfig.class)
@ActiveProfiles("rabbit")
class Test06RabbitClientTest {
@Autowired
RabbitAmqpTemplate template;
@Autowired
RabbitSpecificConfig.RabbitOrderListener listener;
@Autowired
ApplicationContext context;
private static String outcome(java.util.concurrent.Callable<Object> call) {
long start = System.nanoTime();
try {
return "returned " + call.call() + " after " + (System.nanoTime() - start) / 1_000_000 + " ms";
} catch (Throwable e) {
Throwable root = e instanceof ExecutionException && e.getCause() != null ? e.getCause() : e;
while (root.getCause() != null) {
root = root.getCause();
}
String msg = String.valueOf(root.getMessage()).replace('\n', ' ');
return "threw " + root.getClass().getSimpleName() + ": " + (msg.length() > 120 ? msg.substring(0, 120) + "..." : msg)
+ " after " + (System.nanoTime() - start) / 1_000_000 + " ms";
}
}
@Test
void rabbitSpecific() throws Exception {
try (Transcript t = new Transcript("06-rabbit-client")) {
// 0. What the starter auto-configured: nothing below was written by hand.
t.line("beans from spring-boot-starter-amqp-rabbitmq (no @Bean written for them):");
for (Class<?> type : new Class<?>[] { RabbitAmqpTemplate.class, org.springframework.amqp.rabbitmq.client.RabbitAmqpAdmin.class,
org.springframework.amqp.rabbitmq.client.config.RabbitAmqpListenerContainerFactory.class,
org.springframework.amqp.rabbitmq.client.AmqpConnectionFactory.class }) {
t.line(" %-28s %s", type.getSimpleName(), java.util.Arrays.toString(context.getBeanNamesForType(type)));
assertThat(context.getBeanNamesForType(type)).isNotEmpty();
}
// 1. Topology declared by RabbitAmqpAdmin at start-up, nothing created by hand.
assertThat(Await.until(Duration.ofSeconds(15),
() -> Broker.get("/queues/%2F/orders.rabbit").path("type").asString().equals("quorum"))).isTrue();
JsonNode q = Broker.get("/queues/%2F/orders.rabbit");
JsonNode bindings = Broker.get("/exchanges/%2F/orders.topic/bindings/source");
t.line("declared by RabbitAmqpAdmin:");
t.line(" queue %s type=%s durable=%s", q.path("name").asString(), q.path("type").asString(),
q.path("durable").asBoolean());
t.line(" exchange orders.topic type=%s", Broker.get("/exchanges/%2F/orders.topic").path("type").asString());
for (JsonNode b : bindings) {
t.line(" binding %s -> %s key=%s", b.path("source").asString(), b.path("destination").asString(),
b.path("routing_key").asString());
}
assertThat(bindings).hasSize(1);
// 2. Publish through the exchange with a routing key, wait for the broker's confirmation.
OrderMessage order = new OrderMessage("r-1", "router", 2);
Boolean confirmed = template.convertAndSend(RabbitSpecificConfig.EXCHANGE,
RabbitSpecificConfig.ROUTING_KEY, order).get(10, TimeUnit.SECONDS);
t.line("$ template.convertAndSend(\"orders.topic\", \"orders.created\", order).get() -> %s", confirmed);
assertThat(confirmed).isTrue();
assertThat(Await.until(Duration.ofSeconds(10), () -> listener.received().size() == 1)).isTrue();
t.line("@RabbitListener(queues = \"orders.rabbit\") received %s",
listener.received().get(0));
assertThat(listener.received().get(0)).isEqualTo(order);
// 3. What a bad destination looks like.
t.line("unroutable key : %s", outcome(() -> template.convertAndSend(RabbitSpecificConfig.EXCHANGE,
"orders.unknown", order).get(10, TimeUnit.SECONDS)));
t.line("missing exchange: %s", outcome(() -> template.convertAndSend("no.such.exchange",
RabbitSpecificConfig.ROUTING_KEY, order).get(10, TimeUnit.SECONDS)));
// 4. Connections the broker sees now: the generic starter's and RabbitMQ's own client.
String conns = Broker.ctl("list_connections", "protocol", "user", "client_properties");
boolean amqp10 = conns.contains("{1, 0}");
t.line("$ rabbitmqctl list_connections protocol -> an AMQP 1.0 connection is open: %s", amqp10);
assertThat(amqp10).isTrue();
}
}
}
@@ -1,82 +0,0 @@
package com.ankurm.amqp10;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.client.AmqpClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
/** The same broker queue written by one protocol and read by the other. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@Import(TestBrokerConfig.class)
class Test07InteropTest {
@Autowired
AmqpClient amqpClient;
private static void describe(Transcript t, String label, MessageProperties p, byte[] body) {
t.line("%s", label);
t.line(" body = %s", new String(body, StandardCharsets.UTF_8));
t.line(" messageId = %s", p.getMessageId());
t.line(" correlationId = %s", p.getCorrelationId());
t.line(" contentType = %s", p.getContentType());
t.line(" deliveryMode = %s", p.getReceivedDeliveryMode());
Map<String, Object> headers = new TreeMap<>(p.getHeaders());
t.line(" headers = %s", headers);
}
@Test
void classicAndAmqp10ShareAQueue() throws Exception {
CachingConnectionFactory cf = new CachingConnectionFactory(Broker.CONTAINER.getHost(), Broker.CONTAINER.getAmqpPort());
cf.setUsername("guest");
cf.setPassword("guest");
RabbitTemplate classic = new RabbitTemplate(cf);
try (Transcript t = new Transcript("07-classic-interop")) {
// 1. Classic AMQP 0-9-1 producer -> AMQP 1.0 consumer
Message out = MessageBuilder.withBody("{\"id\":\"i-1\",\"item\":\"classic\",\"qty\":1}".getBytes(StandardCharsets.UTF_8))
.setMessageId("m-classic").setCorrelationId("c-classic").setContentType("application/json")
.setDeliveryMode(MessageDeliveryMode.PERSISTENT).setHeader("tenant", "acme").setHeader("attempt", 3)
.build();
classic.send("", "orders.interop", out);
Message in10 = amqpClient.from("/queues/orders.interop").timeout(Duration.ofSeconds(5)).receive().get();
describe(t, "0-9-1 producer (RabbitTemplate) -> AMQP 1.0 consumer (AmqpClient.receive):", in10.getMessageProperties(), in10.getBody());
assertThat(in10.getMessageProperties().getMessageId()).isEqualTo("m-classic");
assertThat(in10.getMessageProperties().getHeaders()).containsEntry("tenant", "acme");
// 2. AMQP 1.0 producer -> classic consumer
amqpClient.to("/queues/orders.interop").body(new OrderMessage("i-2", "amqp10", 2))
.messageId("m-amqp10").correlationId("c-amqp10").header("tenant", "acme").header("attempt", 3)
.durable(true).creationTime(new Date()).send().get();
Message inClassic = classic.receive("orders.interop", 5000);
assertThat(inClassic).isNotNull();
describe(t, "AMQP 1.0 producer (AmqpClient.to) -> 0-9-1 consumer (RabbitTemplate.receive):",
inClassic.getMessageProperties(), inClassic.getBody());
assertThat(inClassic.getMessageProperties().getMessageId()).isEqualTo("m-amqp10");
// 3. Both protocols are open on the one broker at the same time.
String conns = Broker.ctl("list_connections", "protocol");
long v091 = conns.lines().filter(l -> l.replaceAll("\\s", "").contains("{0,9,1}")).count();
long v10 = conns.lines().filter(l -> l.contains("{1, 0}")).count();
t.line("$ rabbitmqctl list_connections protocol, while both clients are connected:");
t.line(" AMQP 0-9-1 connection open = %s, AMQP 1.0 connection open = %s", v091 >= 1, v10 >= 1);
assertThat(v091).isGreaterThanOrEqualTo(1);
assertThat(v10).isGreaterThanOrEqualTo(1);
} finally {
cf.destroy();
}
}
}
@@ -1,60 +0,0 @@
package com.ankurm.amqp10;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.client.AmqpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ActiveProfiles;
/** Boot 4.2.0 defaults: what a listener that throws does to its consumer. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@Import(TestBrokerConfig.class)
@ActiveProfiles("poison")
class Test08PoisonTest {
@Autowired
AmqpClient amqpClient;
@Autowired
PoisonListeners poison;
@Autowired
org.springframework.context.ApplicationContext ctx;
@Test
void failingListenerKillsItsConsumer() throws Exception {
try (Transcript t = new Transcript("08-poison-default")) {
for (String q : new String[] { "plain", "reject", "manual" }) {
amqpClient.to("/queues/orders.poison." + q).body(new OrderMessage("bad-" + q, "boom", 1)).send().get();
}
assertThat(Await.until(Duration.ofSeconds(15), () -> poison.plainAttempts() == 1
&& poison.rejectAttempts() == 1 && poison.manualAttempts() == 1)).isTrue();
// Consumer counts are sampled, so wait for the broker to notice the consumers are gone.
for (String q : new String[] { "plain", "reject", "manual" }) {
assertThat(Await.until(Duration.ofSeconds(20), () -> Broker.consumers("orders.poison." + q) == 0)).isTrue();
}
// A perfectly good message sent afterwards is never delivered: nobody is listening.
amqpClient.to("/queues/orders.poison.plain").body(new OrderMessage("good-1", "ok", 1)).send().get();
int ready = Broker.awaitDepth("orders.poison.plain", 1);
Thread.sleep(2000);
t.line("container errorHandler (Boot's default factory) = %s", Broker.errorHandlerOf(ctx.getBean("poison-plain")));
assertThat(Broker.errorHandlerOf(ctx.getBean("poison-plain"))).isEqualTo("null");
t.line("one bad message sent to each queue, listener always throws:");
t.line("%-38s %-9s %-9s %s", "listener", "attempts", "consumers", "messages left in queue");
t.line("%-38s %-9d %-9d %d (the bad message was lost; the follow-up is waiting)", "plain exception, autoAccept default",
poison.plainAttempts(), Broker.consumers("orders.poison.plain"), ready);
t.line("%-38s %-9d %-9d %d", "AmqpRejectAndDontRequeueException", poison.rejectAttempts(),
Broker.consumers("orders.poison.reject"), Broker.depth("orders.poison.reject"));
t.line("%-38s %-9d %-9d %d (released back, but nobody is left to take it)", "plain exception, autoAccept=false",
poison.manualAttempts(), Broker.consumers("orders.poison.manual"), Broker.depth("orders.poison.manual"));
t.line("follow-up message good-1 delivered to the plain listener? attempts still = %d", poison.plainAttempts());
assertThat(poison.plainAttempts()).isEqualTo(1);
assertThat(Broker.depth("orders.poison.manual")).isEqualTo(1);
}
}
}
@@ -1,61 +0,0 @@
package com.ankurm.amqp10;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.client.AmqpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ActiveProfiles;
/** The same three failing listeners once the container has an ErrorHandler. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@Import(TestBrokerConfig.class)
@ActiveProfiles({ "poison", "handled" })
class Test09HandledTest {
@Autowired
AmqpClient amqpClient;
@Autowired
PoisonListeners poison;
@Autowired
org.springframework.context.ApplicationContext ctx;
@Test
void errorHandlerKeepsConsumerAlive() throws Exception {
try (Transcript t = new Transcript("09-poison-with-error-handler")) {
t.line("container errorHandler = %s", Broker.errorHandlerOf(ctx.getBean("poison-plain")));
assertThat(Broker.errorHandlerOf(ctx.getBean("poison-plain"))).isNotEqualTo("null");
// Previous test class left messages in these quorum queues; start clean.
for (String q : new String[] { "plain", "reject", "manual" }) {
Broker.purge("orders.poison." + q);
}
int plain0 = poison.plainAttempts();
int reject0 = poison.rejectAttempts();
int manual0 = poison.manualAttempts();
for (String q : new String[] { "plain", "reject", "manual" }) {
amqpClient.to("/queues/orders.poison." + q).body(new OrderMessage("bad-" + q, "boom", 1)).send().get();
}
Thread.sleep(3000);
int plain1 = poison.plainAttempts() - plain0;
int reject1 = poison.rejectAttempts() - reject0;
int manualIn3s = poison.manualAttempts() - manual0;
amqpClient.to("/queues/orders.poison.plain").body(new OrderMessage("good-1", "ok", 1)).send().get();
assertThat(Await.until(Duration.ofSeconds(10), () -> poison.plainAttempts() - plain0 == 2)).isTrue();
t.line("with a container ErrorHandler (HandledFactoryConfig), one bad message per queue:");
t.line("plain exception, autoAccept default : %d attempt(s); follow-up good-1 reached the listener = %s",
plain1, poison.plainAttempts() - plain0 == 2);
t.line("AmqpRejectAndDontRequeueException : %d attempt(s)", reject1);
t.line("plain exception, autoAccept=false : %d attempts in 3 seconds (figure varies per run, still counting)", manualIn3s);
t.line("queue orders.poison.manual depth now : %d", Broker.depth("orders.poison.manual"));
assertThat(plain1).isEqualTo(1);
assertThat(reject1).isEqualTo(1);
assertThat(manualIn3s).isGreaterThan(10);
}
}
}
@@ -1,20 +0,0 @@
package com.ankurm.amqp10;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.testcontainers.rabbitmq.RabbitMQContainer;
/**
* {@code @ServiceConnection} on a RabbitMQContainer feeds Boot's AmqpConnectionDetails (the
* generic AMQP 1.0 starter ships its own factory for it), so no spring.amqp.* property is set by hand.
*/
@TestConfiguration(proxyBeanMethods = false)
public class TestBrokerConfig {
@Bean
@ServiceConnection
RabbitMQContainer broker() {
return Broker.CONTAINER;
}
}
@@ -1,37 +0,0 @@
package com.ankurm.amqp10;
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. The 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);
}
}
}
-1
View File
@@ -1 +0,0 @@
target/
-61
View File
@@ -1,61 +0,0 @@
# 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.
@@ -1,4 +0,0 @@
$ 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
@@ -1,12 +0,0 @@
$ 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
@@ -1,4 +0,0 @@
$ 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
@@ -1,14 +0,0 @@
$ 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
@@ -1,14 +0,0 @@
$ 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
@@ -1,17 +0,0 @@
$ 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
@@ -1,25 +0,0 @@
$ 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
@@ -1,2 +0,0 @@
$ 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.
@@ -1,3 +0,0 @@
$ 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
@@ -1,2 +0,0 @@
$ 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
@@ -1,9 +0,0 @@
$ 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
@@ -1,5 +0,0 @@
$ 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
@@ -1,16 +0,0 @@
$ 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
@@ -1,6 +0,0 @@
$ 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
@@ -1,14 +0,0 @@
$ 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
@@ -1,83 +0,0 @@
<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
@@ -1,9 +0,0 @@
#!/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
@@ -1,8 +0,0 @@
#!/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
@@ -1,14 +0,0 @@
#!/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
@@ -1,35 +0,0 @@
#!/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
@@ -1,6 +0,0 @@
#!/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'
@@ -1,12 +0,0 @@
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);
}
}
@@ -1,5 +0,0 @@
package com.ankurm.cloudstream;
/** What the function emits and the consumer receives. */
public record Invoice(String orderId, String customerId, double total) {
}
@@ -1,5 +0,0 @@
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) {
}
@@ -1,62 +0,0 @@
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());
};
}
}
@@ -1,14 +0,0 @@
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
@@ -1,27 +0,0 @@
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
@@ -1,37 +0,0 @@
# 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
@@ -1,25 +0,0 @@
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();
}
}
@@ -1,120 +0,0 @@
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);
}
}
}
@@ -1,108 +0,0 @@
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();
}
}
@@ -1,102 +0,0 @@
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);
}
}
@@ -1,90 +0,0 @@
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");
}
}
}
@@ -1,79 +0,0 @@
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);
}
}
}
}
@@ -1,72 +0,0 @@
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");
}
}
}
@@ -1,85 +0,0 @@
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*$", ""));
}
}
}
@@ -1,36 +0,0 @@
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);
}
}
}
-2
View File
@@ -1,2 +0,0 @@
target/
*.log
-62
View File
@@ -1,62 +0,0 @@
# debezium-cdc
Companion code for the ankurm.com post *Debezium CDC with Spring Boot: Stream Postgres Changes to Kafka (and When to Prefer the Outbox)*.
One Postgres 18 database, one Kafka 4.4 broker, and Debezium running two ways against the same tables:
* **Kafka Connect** with the Debezium Postgres connector (`connect/*.json`, registered over REST).
* **The embedded engine** inside a Spring Boot app (`EmbeddedDebezium.java`), forwarding to Kafka with `KafkaTemplate`.
No `docs/` folder: the explanations live in the post, every transcript lives in `output/`.
## Versions (all read from Maven Central or the image, not from announcements)
| Part | Version |
|---|---|
| JDK | Temurin 25.0.5.1 |
| Spring Boot | 4.2.0 (Spring for Apache Kafka 4.2.0, kafka-clients 4.4.0) |
| Debezium | 3.7.1.Final (engine and the `quay.io/debezium/connect` image; 3.8.0.Alpha2 exists but is not GA) |
| Postgres | 18.7 (`quay.io/debezium/postgres:18`, `wal_level=logical` preset) |
| Kafka broker | `apache/kafka:4.4.0`, KRaft, 3 partitions per auto-created topic |
| Kafka Connect runtime inside the Debezium image | 4.3.1 |
## Run it
```bash
export JDK25_HOME=/path/to/jdk-25 # defaults to this author's sandbox path
./scripts/run-all.sh # fresh stack, builds, runs every scenario, rewrites output/ (about 12 minutes)
```
or step by step: `./scripts/up.sh`, then `./scripts/01-logical-replication.sh` and so on in order. The scenarios
build on each other (01 registers the connector 02 to 04 read from).
## Layout
| Path | What it is |
|---|---|
| `docker-compose.yml` | Postgres, Kafka, Kafka Connect |
| `sql/init.sql` | `orders`, `outbox`, `noise`, `heartbeat` tables and two seed rows |
| `connect/orders-connector.json` | Connector for the business table |
| `connect/outbox-connector.json` | Connector for the outbox table with the `EventRouter` transform |
| `src/main/java/com/ankurm/cdc/EmbeddedDebezium.java` | The embedded engine as a Spring `SmartLifecycle` bean |
| `src/main/java/com/ankurm/cdc/OrderChangeListener.java` | A plain `@KafkaListener` that handles tombstones and duplicates |
| `src/main/java/com/ankurm/cdc/ChangeEvent.java` | Reads the envelope (same for embedded and Connect) |
| `src/test/java/com/ankurm/cdc/ChangeEventTest.java` | Pins the envelope parsing, no infrastructure needed |
## Output index
| File | Shows |
|---|---|
| `output/01-logical-replication.txt` | Server settings, a `test_decoding` peek at the raw logical stream, the slot and publication the connector creates |
| `output/02-event-format.txt` | Snapshot, insert, update, delete and tombstone envelopes under the default replica identity |
| `output/03-replica-identity.txt` | `REPLICA IDENTITY FULL`, and an `ALTER TABLE ADD COLUMN` on a live connector |
| `output/04-ordering.txt` | Per-key order, no global order, one transaction spread across partitions |
| `output/05-outbox.txt` | `EventRouter` output, including an outbox row inserted and deleted in one transaction |
| `output/06-wal-retention.txt` | WAL pinned by a quiet slot, by an orphaned slot, and the heartbeat fix |
| `output/07-embedded.txt` | The embedded engine, a diff against the Connect event, and a `kill -9` redelivery |
## Things this module does not do
* No schema registry or Avro: JSON without the schema wrapper, so the transcripts are readable.
* No exactly-once claim anywhere: the redelivery in `07` is the point.
* Nothing here is hardened for production (plaintext passwords in compose, one broker, replication factor 1).
@@ -1,21 +0,0 @@
{
"name": "orders-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "postgres",
"database.port": "5432",
"database.user": "demo",
"database.password": "demo",
"database.dbname": "shop",
"topic.prefix": "shop",
"table.include.list": "public.orders",
"plugin.name": "pgoutput",
"slot.name": "connect_orders",
"publication.name": "connect_orders_pub",
"publication.autocreate.mode": "filtered",
"key.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"key.converter.schemas.enable": "false",
"value.converter.schemas.enable": "false"
}
}
@@ -1,31 +0,0 @@
{
"name": "outbox-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "postgres",
"database.port": "5432",
"database.user": "demo",
"database.password": "demo",
"database.dbname": "shop",
"topic.prefix": "shopoutbox",
"table.include.list": "public.outbox",
"plugin.name": "pgoutput",
"slot.name": "connect_outbox",
"publication.name": "connect_outbox_pub",
"publication.autocreate.mode": "filtered",
"tombstones.on.delete": "false",
"key.converter": "org.apache.kafka.connect.storage.StringConverter",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schemas.enable": "false",
"transforms": "outbox",
"transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter",
"transforms.outbox.table.field.event.id": "id",
"transforms.outbox.table.field.event.key": "aggregateid",
"transforms.outbox.table.field.event.type": "type",
"transforms.outbox.table.field.event.payload": "payload",
"transforms.outbox.route.by.field": "aggregatetype",
"transforms.outbox.route.topic.replacement": "outbox.event.${routedByValue}",
"transforms.outbox.table.expand.json.payload": "true",
"transforms.outbox.table.fields.additional.placement": "type:header:eventType"
}
}
-42
View File
@@ -1,42 +0,0 @@
# Postgres 18 (wal_level=logical already set by the Debezium image), Kafka 4.4 in KRaft mode, Kafka Connect with Debezium 3.7.1.
services:
postgres:
image: quay.io/debezium/postgres:18
environment:
POSTGRES_USER: demo
POSTGRES_PASSWORD: demo
POSTGRES_DB: shop
ports: ["5432:5432"]
volumes:
- ./sql/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
kafka:
image: apache/kafka:4.4.0
ports: ["9092:9092"]
environment:
KAFKA_NODE_ID: 1
KAFKA_PROCESS_ROLES: broker,controller
KAFKA_LISTENERS: INTERNAL://:19092,EXTERNAL://:9092,CONTROLLER://:9093
KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:19092,EXTERNAL://localhost:9092
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT,CONTROLLER:PLAINTEXT
KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
KAFKA_NUM_PARTITIONS: 3
connect:
image: quay.io/debezium/connect:3.7.1.Final
depends_on: [kafka, postgres]
ports: ["8083:8083"]
environment:
BOOTSTRAP_SERVERS: kafka:19092
GROUP_ID: cdc-connect
CONFIG_STORAGE_TOPIC: connect_configs
OFFSET_STORAGE_TOPIC: connect_offsets
STATUS_STORAGE_TOPIC: connect_statuses
CONFIG_STORAGE_REPLICATION_FACTOR: 1
OFFSET_STORAGE_REPLICATION_FACTOR: 1
STATUS_STORAGE_REPLICATION_FACTOR: 1
# Kafka Connect's default is 60000. Shortened so the WAL-retention demo does not need minute-long waits.
OFFSET_FLUSH_INTERVAL_MS: 10000
@@ -1,69 +0,0 @@
### Server settings that make CDC possible
postgres
-----------------------------------------------------------------
PostgreSQL 18.7 (Debian 18.7-1.pgdg12+5) on x86_64-pc-linux-gnu
(1 row)
wal_level
-----------
logical
(1 row)
max_replication_slots
-----------------------
4
(1 row)
max_wal_senders
-----------------
4
(1 row)
### Before any connector: no slots, no publications
slots
-------
0
(1 row)
publications
--------------
0
(1 row)
### What logical decoding produces, read with the built-in test_decoding plugin on a throwaway slot
data
----------------------------------------------------------------------
BEGIN 770
table public.noise: INSERT: id[bigint]:1 payload[text]:'hello'
COMMIT 770
BEGIN 771
table public.noise: UPDATE: id[bigint]:1 payload[text]:'hello again'
COMMIT 771
BEGIN 772
table public.noise: DELETE: id[bigint]:1
COMMIT 772
(9 rows)
### Register the Debezium connector (Kafka Connect, pgoutput) and wait for it
register 201
connector: RUNNING ['RUNNING']
### What the connector created inside Postgres
slot_name | plugin | slot_type | active
----------------+----------+-----------+--------
connect_orders | pgoutput | logical | t
(1 row)
pubname | puballtables | pubinsert | pubupdate | pubdelete | pubtruncate
--------------------+--------------+-----------+-----------+-----------+-------------
connect_orders_pub | f | t | t | t | t
(1 row)
pubname | schemaname | tablename
--------------------+------------+-----------
connect_orders_pub | public | orders
(1 row)
-51
View File
@@ -1,51 +0,0 @@
### Replica identity of orders (d = default, primary key only)
relname | relreplident
---------+--------------
orders | d
(1 row)
### Four statements, one transaction each
### Topic shop.public.orders in WAL order (p = partition). The two op=r records are the initial snapshot.
p=1 op=r key={"id":2} lsn=30425656 txId=774 snapshot=last before=null after={"id":2,"customer":"ravi","status":"NEW","amount_cents":2500}
p=0 op=r key={"id":1} lsn=30425656 txId=774 snapshot=first before=null after={"id":1,"customer":"asha","status":"NEW","amount_cents":1500}
p=0 op=c key={"id":3} lsn=30425880 txId=775 snapshot=false before=null after={"id":3,"customer":"meera","status":"NEW","amount_cents":999}
p=0 op=u key={"id":3} lsn=30426168 txId=776 snapshot=false before=null after={"id":3,"customer":"meera","status":"PAID","amount_cents":999}
p=0 op=u key={"id":3} lsn=30426312 txId=777 snapshot=false before=null after={"id":3,"customer":"meera","status":"PAID","amount_cents":1099}
p=0 op=d key={"id":3} lsn=30426456 txId=778 snapshot=false before={"id":3,"customer":"","status":"","amount_cents":0} after=null
p=0 key={"id":3} TOMBSTONE (null value)
### The raw insert envelope for id 3, exactly as Kafka stores it (value, pretty-printed with jq)
{
"before": null,
"after": {
"id": 3,
"customer": "meera",
"status": "NEW",
"amount_cents": 999
},
"source": {
"version": "3.7.1.Final",
"connector": "postgresql",
"name": "shop",
"ts_ms": 1795939109105,
"snapshot": "false",
"db": "shop",
"sequence": "[null,\"30425880\"]",
"ts_us": 1795939109105717,
"ts_ns": 1795939109105717000,
"schema": "public",
"table": "orders",
"txId": 775,
"lsn": 30425880,
"xmin": null,
"origin": null,
"origin_lsn": null
},
"transaction": null,
"op": "c",
"ts_ms": 1795939109620,
"ts_us": 1795939109620915,
"ts_ns": 1795939109620915228
}
@@ -1,20 +0,0 @@
### REPLICA IDENTITY DEFAULT: update and delete of order 4
p=2 op=c key={"id":4} lsn=30441152 txId=779 snapshot=false before=null after={"id":4,"customer":"dev","status":"NEW","amount_cents":500}
p=2 op=u key={"id":4} lsn=30441344 txId=780 snapshot=false before=null after={"id":4,"customer":"dev","status":"PAID","amount_cents":500}
p=2 op=d key={"id":4} lsn=30441512 txId=781 snapshot=false before={"id":4,"customer":"","status":"","amount_cents":0} after=null
p=2 key={"id":4} TOMBSTONE (null value)
### Switch the table to REPLICA IDENTITY FULL
relname | relreplident
---------+--------------
orders | f
(1 row)
### Same three statements for order 5
p=2 op=c key={"id":5} lsn=30442128 txId=783 snapshot=false before=null after={"id":5,"customer":"kiran","status":"NEW","amount_cents":700}
p=2 op=u key={"id":5} lsn=30442320 txId=784 snapshot=false before={"id":5,"customer":"kiran","status":"NEW","amount_cents":700} after={"id":5,"customer":"kiran","status":"PAID","amount_cents":700}
p=2 op=d key={"id":5} lsn=30442488 txId=785 snapshot=false before={"id":5,"customer":"kiran","status":"PAID","amount_cents":700} after=null
p=2 key={"id":5} TOMBSTONE (null value)
### Add a column while the connector is running; the next event carries it, no restart needed
p=0 op=u key={"id":1} lsn=30454520 txId=787 snapshot=false before={"id":1,"customer":"asha","status":"NEW","amount_cents":1500,"note":null} after={"id":1,"customer":"asha","status":"NEW","amount_cents":1500,"note":"gift wrap"}
-21
View File
@@ -1,21 +0,0 @@
### Topic layout
Topic: shop.public.orders TopicId: e8p9s2PcSK6mPO3bvQRmyA PartitionCount: 3 ReplicationFactor: 1 Configs: min.insync.replicas=1
### Write: 6 orders (ids 10..15), then 4 rounds of single-row updates, then one transaction that updates 10, then 12, then 13
### Which partition each key landed on, and whether its events stayed in WAL order inside that partition
key 10: partitions=['1'] events=6 lsn strictly increasing in offset order=True
key 11: partitions=['1'] events=5 lsn strictly increasing in offset order=True
key 12: partitions=['2'] events=6 lsn strictly increasing in offset order=True
key 13: partitions=['0'] events=6 lsn strictly increasing in offset order=True
key 14: partitions=['0'] events=5 lsn strictly increasing in offset order=True
key 15: partitions=['0'] events=5 lsn strictly increasing in offset order=True
### Reading partition 0, then 1, then 2 (what the broker stores): is the LSN sequence globally increasing?
lsn sequence head: [30455336, 30455528, 30455720, 30456392, 30456552, 30456712, 30457352, 30457512]
globally increasing across partitions: False
events per partition: {'0': 16, '1': 11, '2': 6}
### The multi-statement transaction (statuses TX-A, TX-B, TX-C): one txId, increasing lsn, three different keys
status=TX-A key=10 partition=1 lsn=30459776 txId=818
status=TX-B key=12 partition=2 lsn=30459896 txId=818
status=TX-C key=13 partition=0 lsn=30460016 txId=818
-14
View File
@@ -1,14 +0,0 @@
### Register the outbox connector (EventRouter single message transform)
register 201
### One transaction writes the business row AND the outbox row
### A second transaction inserts an outbox row and deletes it before committing (the 'clean up as you go' habit)
outbox rows left in the table: 1
### Topic outbox.event.Order (headers | key | value; the four __debezium.context.* headers are trimmed with sed)
id:00000000-0000-0000-0000-000000000021,eventType:OrderCreated | 21 | {"orderId":21,"customer":"omkar","amountCents":100}
id:00000000-0000-0000-0000-000000000020,eventType:OrderCreated | 20 | {"orderId":20,"customer":"zoya","amountCents":4200}
### Topics that exist for this connector
outbox.event.Order
-44
View File
@@ -1,44 +0,0 @@
### Safety valve: the default cap on WAL a slot may pin (-1 = unlimited)
max_slot_wal_keep_size
------------------------
-1
(1 row)
### Baseline: both connectors running, nothing unusual written
slot_name | active | wal_kept_for_slot | unconfirmed
----------------+--------+-------------------+-------------
connect_orders | t | 2752 bytes | 2752 bytes
connect_outbox | t | 1064 bytes | 432 bytes
(2 rows)
### Failure 1: healthy connectors, but all the writes go to a table nobody captures (100,000 rows, about 33 MB of WAL)
slot_name | active | wal_kept_for_slot | unconfirmed
----------------+--------+-------------------+-------------
connect_orders | t | 33 MB | 33 MB
connect_outbox | t | 33 MB | 33 MB
(2 rows)
### Failure 2: delete the outbox connector. Kafka Connect does not drop its slot.
slot_name | active | wal_kept_for_slot | unconfirmed
----------------+--------+-------------------+-------------
connect_orders | t | 65 MB | 65 MB
connect_outbox | f | 65 MB | 65 MB
(2 rows)
### Fix for 2: drop the orphaned slot by hand
slot_name | active | wal_kept_for_slot | unconfirmed
----------------+--------+-------------------+-------------
connect_orders | t | 65 MB | 65 MB
(1 row)
### Fix for 1: heartbeat.interval.ms plus a heartbeat.action.query that writes to a captured table (public.heartbeat)
slot_name | active | wal_kept_for_slot | unconfirmed
----------------+--------+-------------------+-------------
connect_orders | t | 656 bytes | 656 bytes
(1 row)
-39
View File
@@ -1,39 +0,0 @@
### Start the Spring Boot app with the embedded engine (slot embedded_orders, topic prefix embedded)
snapshot rows delivered by the engine: 9
slot_name | plugin | active
-----------------+----------+--------
embedded_orders | pgoutput | t
(1 row)
### Insert, update and delete order 30, and the app's own view of them (EMBEDDED = engine callback, LISTENER = @KafkaListener on embedded.public.orders)
EMBEDDED op=c key={"id":30} lsn=99363544 before=null after={"id":30,"customer":"tara","status":"NEW","amount_cents":300,"note":null}
LISTENER partition=0 offset=5 op=c key={"id":30} lsn=99363544 before=null after={"id":30,"customer":"tara","status":"NEW","amount_cents":300,"note":null}
EMBEDDED op=u key={"id":30} lsn=99363736 before={"id":30,"customer":"tara","status":"NEW","amount_cents":300,"note":null} after={"id":30,"customer":"tara","status":"PAID","amount_cents":300,"note":null}
LISTENER partition=0 offset=6 op=u key={"id":30} lsn=99363736 before={"id":30,"customer":"tara","status":"NEW","amount_cents":300,"note":null} after={"id":30,"customer":"tara","status":"PAID","amount_cents":300,"note":null}
EMBEDDED op=d key={"id":30} lsn=99363904 before={"id":30,"customer":"tara","status":"PAID","amount_cents":300,"note":null} after=null
EMBEDDED key={"id":30} TOMBSTONE (null value)
LISTENER partition=0 offset=7 op=d key={"id":30} lsn=99363904 before={"id":30,"customer":"tara","status":"PAID","amount_cents":300,"note":null} after=null
LISTENER partition=0 offset=8 key={"id":30} TOMBSTONE (ignored)
### Same UPDATE, seen by Kafka Connect (topic shop.public.orders) and by the embedded engine (topic embedded.public.orders): what differs?
5c5
< "name": "shop",
---
> "name": "embedded",
### At-least-once: offsets are flushed every 60 s (Debezium's default). Wait 65 s, then three updates, then kill -9 the JVM
killed. Events the first run delivered for key id=1 after the wait:
lsn=99384632 status set to A0
lsn=99385008 status set to A1
lsn=99385192 status set to A2
### Restart the app (same offset file, same slot)
EMBEDDED events in the second run (anything here is a redelivery):
lsn=99385008 status set to A1
lsn=99385192 status set to A2
### What a downstream consumer sees on embedded.public.orders: records per (key, lsn) for the three A updates
1 status=A0 lsn=99384632
2 status=A1 lsn=99385008
2 status=A2 lsn=99385192
-65
View File
@@ -1,65 +0,0 @@
<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>debezium-cdc</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<java.version>25</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Not managed by the Boot BOM. 3.7.1.Final is the newest Final on Maven Central (3.8.0.Alpha2 is newer but not GA). -->
<debezium.version>3.7.1.Final</debezium.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jackson</artifactId>
</dependency>
<!-- The embedded engine: the Debezium Postgres connector running inside this JVM, no Kafka Connect cluster. -->
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-api</artifactId>
<version>${debezium.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-embedded</artifactId>
<version>${debezium.version}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-postgres</artifactId>
<version>${debezium.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -1,33 +0,0 @@
#!/usr/bin/env bash
# What "logical replication" gives Debezium: a replication slot, a publication, and a decoded stream of row changes.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/01-logical-replication.txt
mkdir -p output
{
echo "### Server settings that make CDC possible"
sqlp -c "select split_part(version(), ',', 1) as postgres" -c "show wal_level" -c "show max_replication_slots" -c "show max_wal_senders"
echo
echo "### Before any connector: no slots, no publications"
sqlp -c "select count(*) as slots from pg_replication_slots" -c "select count(*) as publications from pg_publication"
echo
echo "### What logical decoding produces, read with the built-in test_decoding plugin on a throwaway slot"
sql -c "select pg_create_logical_replication_slot('peek', 'test_decoding')" >/dev/null
sql -c "insert into noise(payload) values ('hello')" -c "update noise set payload = 'hello again' where payload = 'hello'" -c "delete from noise where payload = 'hello again'"
sqlp -c "select data from pg_logical_slot_get_changes('peek', null, null)"
sql -c "select pg_drop_replication_slot('peek')" >/dev/null
echo
echo "### Register the Debezium connector (Kafka Connect, pgoutput) and wait for it"
register connect/orders-connector.json
wait_running orders-connector
echo "connector: $(connector_state orders-connector)"
echo
echo "### What the connector created inside Postgres"
sqlp -c "select slot_name, plugin, slot_type, active from pg_replication_slots"
sqlp -c "select pubname, puballtables, pubinsert, pubupdate, pubdelete, pubtruncate from pg_publication"
sqlp -c "select pubname, schemaname, tablename from pg_publication_tables"
} 2>&1 | tee "$OUT"
-26
View File
@@ -1,26 +0,0 @@
#!/usr/bin/env bash
# The change-event envelope: snapshot reads, then insert, update, delete (and the tombstone) with the default replica identity.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/02-event-format.txt
mkdir -p output
{
echo "### Replica identity of orders (d = default, primary key only)"
sqlp -c "select relname, relreplident from pg_class where relname = 'orders'"
echo
echo "### Four statements, one transaction each"
sql -c "insert into orders values (3, 'meera', 'NEW', 999)"
sql -c "update orders set status = 'PAID' where id = 3"
sql -c "update orders set amount_cents = 1099 where id = 3"
sql -c "delete from orders where id = 3"
sleep 4
echo
echo "### Topic shop.public.orders in WAL order (p = partition). The two op=r records are the initial snapshot."
kafka_consume shop.public.orders 6000 | summarize --sort-lsn
echo
echo "### The raw insert envelope for id 3, exactly as Kafka stores it (value, pretty-printed with jq)"
kafka_consume shop.public.orders 6000 | awk -F'|' '$2 == "{\"id\":3}" && $3 ~ /"op":"c"/ {print $3}' | jq .
} 2>&1 | tee "$OUT"
@@ -1,35 +0,0 @@
#!/usr/bin/env bash
# Why an update has before=null, why a delete has placeholder values, and what REPLICA IDENTITY FULL changes.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/03-replica-identity.txt
mkdir -p output
latest() { # latest <key-id> <n> : last n events for an order id, in WAL order
kafka_consume shop.public.orders 6000 | grep -F "|{\"id\":$1}|" | summarize --sort-lsn | tail -"$2"
}
{
sql -c "insert into orders values (4, 'dev', 'NEW', 500)"
echo "### REPLICA IDENTITY DEFAULT: update and delete of order 4"
sql -c "update orders set status = 'PAID' where id = 4"
sql -c "delete from orders where id = 4"
sleep 4
latest 4 4
echo
echo "### Switch the table to REPLICA IDENTITY FULL"
sql -c "alter table orders replica identity full"
sqlp -c "select relname, relreplident from pg_class where relname = 'orders'"
sql -c "insert into orders values (5, 'kiran', 'NEW', 700)"
sql -c "update orders set status = 'PAID' where id = 5"
sql -c "delete from orders where id = 5"
sleep 4
echo "### Same three statements for order 5"
latest 5 4
echo
echo "### Add a column while the connector is running; the next event carries it, no restart needed"
sql -c "alter table orders add column note text"
sql -c "update orders set note = 'gift wrap' where id = 1"
sleep 4
latest 1 1
} 2>&1 | tee "$OUT"
-58
View File
@@ -1,58 +0,0 @@
#!/usr/bin/env bash
# What ordering does CDC to Kafka really guarantee? Per key, yes. Across keys, no. Inside one transaction, only in the WAL.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/04-ordering.txt
mkdir -p output
{
echo "### Topic layout"
docker compose exec -T kafka $KT/kafka-topics.sh --bootstrap-server kafka:19092 --describe --topic shop.public.orders 2>/dev/null | head -1 | tr '\t' ' '
echo
echo "### Write: 6 orders (ids 10..15), then 4 rounds of single-row updates, then one transaction that updates 10, then 12, then 13"
for id in 10 11 12 13 14 15; do sql -c "insert into orders(id, customer, status, amount_cents) values ($id, 'c$id', 'NEW', 100)"; done
for round in 1 2 3 4; do
for id in 10 11 12 13 14 15; do sql -c "update orders set status = 'R$round' where id = $id"; done
done
sql <<'SQL'
begin;
update orders set status = 'TX-A' where id = 10;
update orders set status = 'TX-B' where id = 12;
update orders set status = 'TX-C' where id = 13;
commit;
SQL
sleep 5
kafka_consume shop.public.orders 8000 | grep -E '\|\{"id":1[0-5]\}\|' > /tmp/cdc04.txt
python3 -I - <<'PY'
import json, collections
by_part = collections.OrderedDict((p, []) for p in "012")
for line in open("/tmp/cdc04.txt"):
part, key, value = line.rstrip("\n").split("|", 2)
if value == "null": continue
v = json.loads(value)
by_part[part].append((json.loads(key)["id"], v["op"], v["source"]["lsn"], v["source"]["txId"], v["after"]["status"] if v["after"] else None))
print("### Which partition each key landed on, and whether its events stayed in WAL order inside that partition")
keys = collections.defaultdict(list)
for part, evs in by_part.items():
for e in evs: keys[e[0]].append((part, e[2]))
for k in sorted(keys):
parts = {p for p, _ in keys[k]}
lsns = [l for _, l in keys[k]]
print(f"key {k}: partitions={sorted(parts)} events={len(lsns)} lsn strictly increasing in offset order={lsns == sorted(lsns) and len(set(lsns)) == len(lsns)}")
print()
print("### Reading partition 0, then 1, then 2 (what the broker stores): is the LSN sequence globally increasing?")
seq = [e[2] for evs in by_part.values() for e in evs]
print("lsn sequence head:", seq[:8])
print("globally increasing across partitions:", seq == sorted(seq))
print("events per partition:", {p: len(e) for p, e in by_part.items()})
print()
print("### The multi-statement transaction (statuses TX-A, TX-B, TX-C): one txId, increasing lsn, three different keys")
tx_rows = [(lsn, st, k, part, tx) for part, evs in by_part.items() for k, op, lsn, tx, st in evs if st and st.startswith("TX-")]
for lsn, st, k, part, tx in sorted(tx_rows): # sorted by LSN: the order Postgres committed the statements in
print(f"status={st} key={k} partition={part} lsn={lsn} txId={tx}")
PY
} 2>&1 | tee "$OUT"
-46
View File
@@ -1,46 +0,0 @@
#!/usr/bin/env bash
# The same connector technology, pointed at an outbox table instead of the business table, with the EventRouter SMT.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/05-outbox.txt
mkdir -p output
{
echo "### Register the outbox connector (EventRouter single message transform)"
register connect/outbox-connector.json
wait_running outbox-connector
echo
echo "### One transaction writes the business row AND the outbox row"
sql <<'SQL'
begin;
insert into orders(id, customer, status, amount_cents) values (20, 'zoya', 'NEW', 4200);
insert into outbox(id, aggregatetype, aggregateid, type, payload)
values ('00000000-0000-0000-0000-000000000020', 'Order', '20', 'OrderCreated',
'{"orderId":20,"customer":"zoya","amountCents":4200}');
commit;
SQL
echo
echo "### A second transaction inserts an outbox row and deletes it before committing (the 'clean up as you go' habit)"
sql <<'SQL'
begin;
insert into outbox(id, aggregatetype, aggregateid, type, payload)
values ('00000000-0000-0000-0000-000000000021', 'Order', '21', 'OrderCreated',
'{"orderId":21,"customer":"omkar","amountCents":100}');
delete from outbox where id = '00000000-0000-0000-0000-000000000021';
commit;
SQL
echo "outbox rows left in the table: $(sql -t -A -c 'select count(*) from outbox')"
sleep 5
echo
echo "### Topic outbox.event.Order (headers | key | value; the four __debezium.context.* headers are trimmed with sed)"
docker compose exec -T kafka $KT/kafka-console-consumer.sh --bootstrap-server kafka:19092 --topic outbox.event.Order \
--from-beginning --timeout-ms 8000 --formatter-property print.headers=true --formatter-property print.key=true \
--formatter-property key.separator=' | ' --formatter-property headers.separator=',' --formatter-property headers.deserializer=org.apache.kafka.common.serialization.StringDeserializer 2>/dev/null \
| sed -e 's/__debezium\.context\.[A-Za-z]*:[^,]*,//g'
echo
echo "### Topics that exist for this connector"
docker compose exec -T kafka $KT/kafka-topics.sh --bootstrap-server kafka:19092 --list 2>/dev/null | grep -E '^(outbox|shopoutbox)' || true
} 2>&1 | tee "$OUT"
-46
View File
@@ -1,46 +0,0 @@
#!/usr/bin/env bash
# A replication slot makes Postgres keep WAL until the consumer confirms it. Three ways that goes wrong, and the fixes.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/06-wal-retention.txt
mkdir -p output
slots() {
sqlp -c "select slot_name, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) as wal_kept_for_slot,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) as unconfirmed
from pg_replication_slots order by slot_name"
}
burst() { sql -c "insert into noise(payload) select repeat('x', 200) from generate_series(1, 100000)"; }
{
echo "### Safety valve: the default cap on WAL a slot may pin (-1 = unlimited)"
sqlp -c "show max_slot_wal_keep_size"
echo
echo "### Baseline: both connectors running, nothing unusual written"
slots
echo
echo "### Failure 1: healthy connectors, but all the writes go to a table nobody captures (100,000 rows, about 33 MB of WAL)"
burst
sleep 15
slots
echo
echo "### Failure 2: delete the outbox connector. Kafka Connect does not drop its slot."
curl -s -X DELETE $CONNECT/connectors/outbox-connector -o /dev/null
sleep 5
burst
slots
echo
echo "### Fix for 2: drop the orphaned slot by hand"
sql -c "select pg_drop_replication_slot('connect_outbox')" >/dev/null
slots
echo
echo "### Fix for 1: heartbeat.interval.ms plus a heartbeat.action.query that writes to a captured table (public.heartbeat)"
curl -s -X PUT -H 'Content-Type: application/json' $CONNECT/connectors/orders-connector/config \
--data "$(jq '.config + {"table.include.list":"public.orders,public.heartbeat","heartbeat.interval.ms":"5000","heartbeat.action.query":"INSERT INTO heartbeat (id, ts) VALUES (1, now()) ON CONFLICT (id) DO UPDATE SET ts = EXCLUDED.ts"}' connect/orders-connector.json)" -o /dev/null
sleep 60
slots
} 2>&1 | tee "$OUT"
-77
View File
@@ -1,77 +0,0 @@
#!/usr/bin/env bash
# The embedded engine: same connector, same envelope, running inside the Spring Boot JVM. Then the at-least-once proof.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/07-embedded.txt
mkdir -p output target
JAR=target/debezium-cdc-1.0.jar
[ -f "$JAR" ] || mvn -B -q package -DskipTests >/dev/null 2>&1
rm -f target/embedded-offsets.dat target/run1.log target/run2.log
start_app() { # start_app <logfile> -> sets APP_PID
java -jar "$JAR" --cdc.embedded.enabled=true --cdc.listener.enabled=true \
--cdc.listener.topic=embedded.public.orders --cdc.embedded.show-raw=true \
> "$1" 2>&1 &
APP_PID=$!
}
wait_for() { # wait_for <logfile> <regex> <seconds>
for i in $(seq 1 "$3"); do grep -q -E "$2" "$1" 2>/dev/null && return 0; sleep 1; done
echo "timed out waiting for $2"; return 1
}
status_lines() { # one line per update of order 1 to A0..A2: its LSN and the status it set
grep -E '^EMBEDDED op=u key=\{"id":1\}' "$1" | sed -E 's/^EMBEDDED op=u key=\{"id":1\} lsn=([0-9]+) .*after=.*"status":"(A[0-9])".*/lsn=\1 status set to \2/' | grep 'status set to A'
}
events() { grep -E '^(EMBEDDED|LISTENER) ' "$1" | sed -e 's/ txId=[0-9]*//'; }
{
echo "### Start the Spring Boot app with the embedded engine (slot embedded_orders, topic prefix embedded)"
start_app target/run1.log
wait_for target/run1.log '^EMBEDDED op=r' 90
sleep 8
echo "snapshot rows delivered by the engine: $(grep -c '^EMBEDDED op=r' target/run1.log)"
sqlp -c "select slot_name, plugin, active from pg_replication_slots where slot_name = 'embedded_orders'"
echo
echo "### Insert, update and delete order 30, and the app's own view of them (EMBEDDED = engine callback, LISTENER = @KafkaListener on embedded.public.orders)"
sql -c "insert into orders(id, customer, status, amount_cents) values (30, 'tara', 'NEW', 300)"
sql -c "update orders set status = 'PAID' where id = 30"
sql -c "delete from orders where id = 30"
wait_for target/run1.log 'LISTENER .*TOMBSTONE' 30
sleep 2
events target/run1.log | grep -E 'key=\{"id":30\}' | cut -c1-230
echo
echo "### Same UPDATE, seen by Kafka Connect (topic shop.public.orders) and by the embedded engine (topic embedded.public.orders): what differs?"
sql -c "update orders set status = 'SHIPPED' where id = 2"
sleep 6
norm='del(.ts_ms,.ts_us,.ts_ns,.source.ts_ms,.source.ts_us,.source.ts_ns) | .source'
kafka_consume shop.public.orders 8000 | awk -F'|' '$2 == "{\"id\":2}" && $3 ~ /SHIPPED/ {print $3}' | jq -S "$norm" > /tmp/connect-src.json
grep '^EMBEDDED-RAW' target/run1.log | sed 's/^EMBEDDED-RAW //' | grep SHIPPED | jq -S "$norm" > /tmp/embedded-src.json
diff /tmp/connect-src.json /tmp/embedded-src.json || true
echo
echo "### At-least-once: offsets are flushed every 60 s (Debezium's default). Wait 65 s, then three updates, then kill -9 the JVM"
sleep 65
sql -c "update orders set status = 'A0' where id = 1"
sleep 2
sql -c "update orders set status = 'A1' where id = 1"
sql -c "update orders set status = 'A2' where id = 1"
wait_for target/run1.log 'LISTENER .*status":"A2"' 30
kill -9 "$APP_PID"; wait "$APP_PID" 2>/dev/null || true
echo "killed. Events the first run delivered for key id=1 after the wait:"
status_lines target/run1.log
echo
echo "### Restart the app (same offset file, same slot)"
start_app target/run2.log
wait_for target/run2.log '^EMBEDDED ' 90
sleep 10
echo "EMBEDDED events in the second run (anything here is a redelivery):"
status_lines target/run2.log
kill "$APP_PID"; wait "$APP_PID" 2>/dev/null || true
echo
echo "### What a downstream consumer sees on embedded.public.orders: records per (key, lsn) for the three A updates"
kafka_consume embedded.public.orders 8000 | summarize | grep -E 'after=\{"id":1,.*"status":"A[012]"' \
| sed -E 's/.* lsn=([0-9]+) .*"status":"(A[012])".*/status=\2 lsn=\1/' | sort | uniq -c
} 2>&1 | tee "$OUT"
-27
View File
@@ -1,27 +0,0 @@
# Sourced by every scenario script. Needs Docker, the compose stack from ../docker-compose.yml, curl, python3.
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
export JAVA_HOME="${JDK25_HOME:-/tmp/tools/jdk-25.0.5.1+2}"
export PATH="$JAVA_HOME/bin:$PATH"
CONNECT=http://localhost:8083
KT=/opt/kafka/bin
sql() { docker compose exec -T postgres psql -U demo -d shop -X -q -v ON_ERROR_STOP=1 "$@"; }
sqlp() { sql -P pager=off "$@"; }
# kafka_consume <topic> [idle-timeout-ms] -> "partition|key|value" lines
kafka_consume() {
docker compose exec -T kafka $KT/kafka-console-consumer.sh --bootstrap-server kafka:19092 --topic "$1" \
--from-beginning --timeout-ms "${2:-6000}" \
--formatter-property print.partition=true --formatter-property print.key=true \
--formatter-property key.separator='|' --formatter-property print.headers=false 2>/dev/null \
| sed -e 's/^Partition:\([0-9]*\)|/\1|/'
}
summarize() { python3 -I "$ROOT/scripts/summarize.py" "$@"; }
register() { # register <connector-json-file>
curl -s -o /dev/null -w "register %{http_code}\n" -X POST -H 'Content-Type: application/json' --data @"$1" $CONNECT/connectors
}
connector_state() { curl -s $CONNECT/connectors/"$1"/status | python3 -I -c 'import json,sys; d=json.load(sys.stdin); print(d["connector"]["state"], [t["state"] for t in d["tasks"]])'; }
wait_running() { for i in $(seq 1 60); do s=$(connector_state "$1" 2>/dev/null || true); case "$s" in "RUNNING ['RUNNING']") return 0;; esac; sleep 1; done; echo "connector $1 not running: $s"; return 1; }
-17
View File
@@ -1,17 +0,0 @@
#!/usr/bin/env bash
# Rebuilds the whole environment from nothing and regenerates every file in output/. Takes about 12 minutes.
# Needs: JDK 25, Maven, Docker (with the compose plugin), curl, jq, python3.
set -eu
cd "$(dirname "$0")/.."
mkdir -p output
# JDK 25 is required (java.version=25). Set JDK25_HOME to one; the default below is this sandbox's.
export JAVA_HOME="${JDK25_HOME:-/tmp/tools/jdk-25.0.5.1+2}"
export PATH="$JAVA_HOME/bin:$PATH"
[ "${SKIP_UP:-}" = 1 ] || ./scripts/up.sh # SKIP_UP=1 reuses a stack that was just created by up.sh
mvn -B -q package # compiles, runs ChangeEventTest, builds the jar the embedded scenario starts
for s in 01-logical-replication 02-event-format 03-replica-identity 04-ordering 05-outbox 06-wal-retention 07-embedded; do
echo "== $s"
./scripts/$s.sh > /dev/null
done
# Machine-specific values do not belong in committed output.
ls -1 output
-29
View File
@@ -1,29 +0,0 @@
"""Reads 'partition|key|value' lines from stdin, prints one compact line per Debezium event.
--sort-lsn : print in WAL order instead of Kafka arrival order. Partitions are read in no particular
order, so this is for display only; a tombstone takes the LSN of the delete before it.
"""
import json, sys
def short(o):
return "null" if o is None else json.dumps(o, separators=(",", ":"))
rows, last_lsn = [], {}
for line in sys.stdin:
line = line.rstrip("\n")
if not line.strip():
continue
part, key, value = line.split("|", 2)
if value == "null":
lsn = last_lsn.get(part, 0)
rows.append((lsn, 1, f"p={part} key={key} TOMBSTONE (null value)"))
continue
v = json.loads(value)
s = v["source"]
last_lsn[part] = s["lsn"]
rows.append((s["lsn"], 0, f"p={part} op={v['op']} key={key} lsn={s['lsn']} txId={s['txId']} snapshot={s['snapshot']} before={short(v['before'])} after={short(v['after'])}"))
if "--sort-lsn" in sys.argv:
rows.sort(key=lambda r: (r[0], r[1]))
for _, _, text in rows:
print(text)
-13
View File
@@ -1,13 +0,0 @@
#!/usr/bin/env bash
# Fresh stack: Postgres 18 + Kafka 4.4 + Kafka Connect (Debezium 3.7.1). Start services one at a time and wait,
# because starting Connect before Kafka is ready only produces noisy restarts.
set -eu
. "$(dirname "$0")/lib.sh"
docker compose down -v >/dev/null 2>&1 || true
docker compose up -d postgres >/dev/null 2>&1
for i in $(seq 1 60); do sql -c 'select 1' >/dev/null 2>&1 && break; sleep 1; done
docker compose up -d kafka >/dev/null 2>&1
for i in $(seq 1 90); do docker compose exec -T kafka $KT/kafka-topics.sh --bootstrap-server kafka:19092 --list >/dev/null 2>&1 && break; sleep 1; done
docker compose up -d connect >/dev/null 2>&1
for i in $(seq 1 180); do curl -s -f $CONNECT/ >/dev/null 2>&1 && break; sleep 2; done
echo "stack is up"
-30
View File
@@ -1,30 +0,0 @@
-- Two tables: a plain business table, and an outbox table used in the last section.
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer text NOT NULL,
status text NOT NULL,
amount_cents integer NOT NULL
);
CREATE TABLE outbox (
id uuid PRIMARY KEY,
aggregatetype text NOT NULL,
aggregateid text NOT NULL,
type text NOT NULL,
payload jsonb NOT NULL
);
-- Seed rows that exist BEFORE any connector starts, so the initial snapshot has something to read.
INSERT INTO orders VALUES (1, 'asha', 'NEW', 1500), (2, 'ravi', 'NEW', 2500);
-- A table nobody captures. Writing to it still produces WAL, which matters in the "slot retains WAL" section.
CREATE TABLE noise (
id bigserial PRIMARY KEY,
payload text NOT NULL
);
-- Written by the connector's heartbeat.action.query so a quiet slot can still move forward (section on WAL retention).
CREATE TABLE heartbeat (
id integer PRIMARY KEY,
ts timestamptz
);
@@ -1,11 +0,0 @@
package com.ankurm.cdc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CdcApplication {
public static void main(String[] args) {
SpringApplication.run(CdcApplication.class, args);
}
}
@@ -1,34 +0,0 @@
package com.ankurm.cdc;
import tools.jackson.databind.JsonNode;
/**
* The part of a Debezium change-event envelope this module cares about, read from the JSON value.
* Works for both the embedded engine and Kafka Connect, because both emit the same envelope.
*/
public record ChangeEvent(String op, JsonNode key, JsonNode before, JsonNode after, long lsn, long txId, String snapshot) {
public static ChangeEvent parse(tools.jackson.databind.ObjectMapper mapper, String key, String value) {
JsonNode k = key == null ? null : mapper.readTree(key);
JsonNode v = mapper.readTree(value);
// With schemas.enable=true the envelope is wrapped in {"schema":..., "payload":...}.
JsonNode p = v.has("payload") ? v.get("payload") : v;
JsonNode src = p.get("source");
return new ChangeEvent(
p.get("op").asString(),
k != null && k.has("payload") ? k.get("payload") : k,
p.get("before"), p.get("after"),
src.get("lsn").asLong(), src.get("txId").asLong(),
src.has("snapshot") ? src.get("snapshot").asString() : "false");
}
/** One compact line, the same shape for every transcript in output/. */
public String summary() {
return "op=%s key=%s lsn=%d txId=%d before=%s after=%s".formatted(
op, key, lsn, txId, nullable(before), nullable(after));
}
private static String nullable(JsonNode n) {
return n == null || n.isNull() ? "null" : n.toString();
}
}

Some files were not shown because too many files have changed in this diff Show More