Compare commits
2
Commits
main
..
2919282a5c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2919282a5c | ||
|
|
8b5587cf88 |
@@ -1,37 +1,21 @@
|
|||||||
# 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 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| [`kafka-basics/`](kafka-basics/README.md) | [Spring Boot 4.1 and Apache Kafka: Producer, Consumer and Serialisation from Scratch](https://ankurm.com/spring-boot-4-1-kafka-producer-consumer-serialisation/) | The on-ramp: what the starter gives you, the two Jackson serializer families, where a key lands and why, and which defaults are Kafka's rather than Spring's |
|
| [`kafka-basics/`](kafka-basics/README.md) | [Spring Boot 4.1 and Apache Kafka: Producer, Consumer and Serialisation from Scratch](https://ankurm.com/spring-boot-4-1-kafka-producer-consumer-serialisation/) | The on-ramp: what the starter gives you, the two Jackson serializer families, where a key lands and why, and which defaults are Kafka's rather than Spring's |
|
||||||
| [`kafka-error-handling/`](kafka-error-handling/README.md) | [Kafka Error Handling with Spring Kafka 4.1: DLT, Retry Topics and Poison Pills](https://ankurm.com/spring-kafka-4-1-error-handling-dlt-retry-topics/) | What the default error handler really does, why a poison pill stops a partition, and what blocking retries cost that retry topics do not |
|
| [`kafka-error-handling/`](kafka-error-handling/README.md) | [Kafka Error Handling with Spring Kafka 4.1: DLT, Retry Topics and Poison Pills](https://ankurm.com/spring-kafka-4-1-error-handling-dlt-retry-topics/) | What the default error handler really does, why a poison pill stops a partition, and what blocking retries cost that retry topics do not |
|
||||||
| [`rabbitmq/`](rabbitmq/README.md) | [Spring Boot and RabbitMQ: Exchanges, Queues, Bindings and a Working Dead-Letter Queue](https://ankurm.com/spring-boot-rabbitmq-exchanges-dead-letter-queue/) | All four exchange types against a real broker, manual acknowledgement, and a dead-letter path exercised through both rejection and TTL expiry |
|
| [`rabbitmq/`](rabbitmq/README.md) | [Spring Boot and RabbitMQ: Exchanges, Queues, Bindings and a Working Dead-Letter Queue](https://ankurm.com/spring-boot-rabbitmq-exchanges-dead-letter-queue/) | All four exchange types against a real broker, manual acknowledgement, and a dead-letter path exercised through both rejection and TTL expiry |
|
||||||
| [`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 |
|
|
||||||
| [`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 two brokers make an instructive pair. Kafka's consumer holds an offset and the broker
|
||||||
nothing about individual records; RabbitMQ's broker owns the message until it is acknowledged and
|
remembers nothing about individual records; RabbitMQ's broker owns the message until it is
|
||||||
can route, expire and dead-letter it on its own; Pulsar keeps the log but lets each subscriber
|
acknowledged and can route, expire and dead-letter it on its own. Almost every difference in how
|
||||||
choose how it is read. Almost every difference in how you handle failure follows from those three
|
you handle failure follows from that one sentence — which is why Kafka needs a retry topic
|
||||||
sentences — which is why Kafka needs a retry topic to do what RabbitMQ does with a queue
|
to do what RabbitMQ does with a queue argument.
|
||||||
argument, and why `broker-comparison` is mostly an argument about where a message lives.
|
|
||||||
|
|
||||||
The last two modules are about the *other* kind of messaging — a connection rather than a
|
|
||||||
broker — and they are deliberately adjacent to the broker modules, because the question
|
|
||||||
"should this be a topic or a stream?" is answered by whether anything needs to survive a dropped
|
|
||||||
connection. Nothing in `sse-websocket` or `protocol-comparison` persists a single message.
|
|
||||||
|
|
||||||
They are meant to be read in order. `kafka-basics` establishes that the default acknowledgement
|
They are meant to be read in order. `kafka-basics` establishes that the default acknowledgement
|
||||||
mode is `BATCH` and therefore that delivery is at-least-once; everything the error-handling
|
mode is `BATCH` and therefore that delivery is at-least-once; everything the error-handling
|
||||||
@@ -45,8 +29,8 @@ Central and from Boot's own `spring-boot-dependencies` POM, rather than from rel
|
|||||||
announcements.
|
announcements.
|
||||||
|
|
||||||
Every module runs its broker without Docker, so the transcripts can be regenerated on any
|
Every module runs its broker without Docker, so the transcripts can be regenerated on any
|
||||||
machine with a JDK: Kafka via the in-process KRaft broker in `spring-kafka-test`, RabbitMQ and
|
machine with a JDK: Kafka via the in-process KRaft broker in `spring-kafka-test`, RabbitMQ via a
|
||||||
Pulsar via real brokers started by the modules' own scripts. Each module also ships a Testcontainers
|
real broker started by the module's own scripts. Each module also ships a Testcontainers
|
||||||
configuration for the cases where the deployed image is what you need to test against.
|
configuration for the cases where the deployed image is what you need to test against.
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
|
|||||||
@@ -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.
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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)
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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>
|
|
||||||
@@ -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"
|
|
||||||
@@ -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,80 +0,0 @@
|
|||||||
# broker-comparison
|
|
||||||
|
|
||||||
Companion project for **Kafka vs RabbitMQ vs Pulsar for Java Teams: A Decision Framework with
|
|
||||||
Benchmarks** on [ankurm.com](https://ankurm.com).
|
|
||||||
|
|
||||||
Three brokers, three questions, one set of measurements. Ordering, replay and consumer scaling are
|
|
||||||
asked identically of all three by driving the client libraries directly, so that what is compared
|
|
||||||
is the brokers' delivery models rather than three sets of Spring defaults. What each Spring
|
|
||||||
integration adds on top is [chapter 6](docs/06-what-spring-adds.md).
|
|
||||||
|
|
||||||
## Verified stack
|
|
||||||
|
|
||||||
| Component | Version | Source of the number |
|
|
||||||
|---|---|---|
|
|
||||||
| JDK (tests) | 25.0.4.1+1 (Temurin) | `java -version` |
|
|
||||||
| JDK (brokers) | 21.0.12.1+1 (Temurin) | `java -version` |
|
|
||||||
| Spring Boot | 4.1.1 | `maven-metadata.xml` on Maven Central |
|
|
||||||
| kafka-clients | 4.2.1 | `spring-boot-dependencies-4.1.1.pom` |
|
|
||||||
| amqp-client | 5.30.0 | `spring-boot-dependencies-4.1.1.pom` |
|
|
||||||
| pulsar-client | 4.2.4 | `spring-boot-dependencies-4.1.1.pom` |
|
|
||||||
| Kafka broker | 4.2.1 (KRaft) | `kafka_2.13-4.2.1.tgz` |
|
|
||||||
| RabbitMQ broker | 3.10.25 | generic-unix tarball |
|
|
||||||
| Pulsar broker | 4.2.4 standalone | `apache-pulsar-4.2.4-bin.tar.gz` |
|
|
||||||
|
|
||||||
RabbitMQ is pinned at 3.10.25 because the box that produced these transcripts has Erlang 24;
|
|
||||||
3.11 and later need Erlang 25. The AMQP 0-9-1 semantics measured here are unchanged in 4.x.
|
|
||||||
|
|
||||||
## Quickstart
|
|
||||||
|
|
||||||
The Kafka measurements need no external broker — `spring-kafka-test` starts a real KRaft broker
|
|
||||||
in-process. The other two need a broker each, and the scripts start both without Docker and
|
|
||||||
without root.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mvn -Dgroups=kafka test
|
|
||||||
|
|
||||||
ERL_ROOT=... RABBITMQ_HOME=... scripts/rabbit-broker.sh
|
|
||||||
mvn -Dgroups=rabbit test
|
|
||||||
|
|
||||||
PULSAR_HOME=... scripts/pulsar-broker.sh
|
|
||||||
mvn -Dgroups=pulsar test
|
|
||||||
|
|
||||||
scripts/footprint.sh kafka|rabbit|pulsar # the operational numbers
|
|
||||||
scripts/run-all.sh # regenerates every docs/output/ file
|
|
||||||
```
|
|
||||||
|
|
||||||
## Documentation
|
|
||||||
|
|
||||||
| Chapter | What it settles |
|
|
||||||
|---|---|
|
|
||||||
| [01 Three models](docs/01-three-models.md) | Where a message lives, and why everything else follows |
|
|
||||||
| [02 Ordering](docs/02-ordering.md) | What survives the second consumer, in all three |
|
|
||||||
| [03 Replay](docs/03-replay.md) | Reading it twice, and the one broker that cannot |
|
|
||||||
| [04 Consumer scaling](docs/04-consumer-scaling.md) | The partition ceiling, and the client buffer that defeats fan-out in the other two |
|
|
||||||
| [05 Operational footprint](docs/05-operational-footprint.md) | Startup, memory, ports, processes, configuration surface |
|
|
||||||
| [06 What Spring adds](docs/06-what-spring-adds.md) | The three integrations, and the Boot 4 starter trap |
|
|
||||||
| [07 The decision table](docs/07-the-decision-table.md) | Every row backed by a measurement, and how to choose |
|
|
||||||
|
|
||||||
## Captured output
|
|
||||||
|
|
||||||
| File | What it shows |
|
|
||||||
|---|---|
|
|
||||||
| [`kafka-ordering.txt`](docs/output/kafka-ordering.txt) | Per-key order kept, global order not — and why A, B and C were the wrong keys to demonstrate it |
|
|
||||||
| [`kafka-replay.txt`](docs/output/kafka-replay.txt) | The same 12 records read three times |
|
|
||||||
| [`kafka-consumer-scaling.txt`](docs/output/kafka-consumer-scaling.txt) | 5 consumers, 3 partitions, 2 idle |
|
|
||||||
| [`rabbit-ordering.txt`](docs/output/rabbit-ordering.txt) | Message 1 finishing tenth |
|
|
||||||
| [`rabbit-replay.txt`](docs/output/rabbit-replay.txt) | 12 messages, then 0, then an empty queue |
|
|
||||||
| [`rabbit-consumer-scaling.txt`](docs/output/rabbit-consumer-scaling.txt) | 40/0/0/0/0 without `basicQos`, 8 each with it |
|
|
||||||
| [`pulsar-ordering.txt`](docs/output/pulsar-ordering.txt) | `Shared` spreading a key, `Key_Shared` pinning it |
|
|
||||||
| [`pulsar-replay.txt`](docs/output/pulsar-replay.txt) | `seek(earliest)` and a new subscription |
|
|
||||||
| [`pulsar-consumer-scaling.txt`](docs/output/pulsar-consumer-scaling.txt) | The 1000-message receiver queue defeating fan-out |
|
|
||||||
| [`footprint.txt`](docs/output/footprint.txt) | Startup, memory, ports and config surface for all three |
|
|
||||||
| [`tests.txt`](docs/output/tests.txt) | The nine tests behind all of the above |
|
|
||||||
|
|
||||||
## What is not measured here
|
|
||||||
|
|
||||||
Throughput. A messages-per-second number from one 2-core container says nothing about any of
|
|
||||||
these brokers, and publishing one would be worse than publishing nothing. The measurements above
|
|
||||||
are structural: they hold on any hardware, because they are properties of the delivery models
|
|
||||||
rather than of the machine.
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
[README](../README.md) · next: [Ordering](02-ordering.md)
|
|
||||||
|
|
||||||
# 1. Three storage models, and everything that follows from them
|
|
||||||
|
|
||||||
Almost every difference between these brokers follows from one sentence about where a message
|
|
||||||
lives.
|
|
||||||
|
|
||||||
- **Kafka** is an append-only log, partitioned. The broker keeps every record for the retention
|
|
||||||
period and remembers nothing about individual consumers except an offset. Reading does not
|
|
||||||
remove anything.
|
|
||||||
- **RabbitMQ** is a router with queues. The broker owns each message until a consumer
|
|
||||||
acknowledges it, and then deletes it. It can route, expire, and dead-letter on its own.
|
|
||||||
- **Pulsar** is a log too, but the cursor and the storage are separate services: brokers are
|
|
||||||
stateless and BookKeeper holds the data. Acknowledgement moves a cursor, and a message is
|
|
||||||
deleted once every subscription has passed it — unless a retention policy says otherwise.
|
|
||||||
|
|
||||||
Read those three sentences again before reading any comparison table, including the one in
|
|
||||||
[chapter 7](07-the-decision-table.md). They predict most of it.
|
|
||||||
|
|
||||||
| | Kafka | RabbitMQ | Pulsar |
|
|
||||||
|---|---|---|---|
|
|
||||||
| unit of parallelism | partition | queue | subscription |
|
|
||||||
| set when | topic is created | queue is declared | consumer subscribes |
|
|
||||||
| consuming | moves an offset | deletes the message | moves a cursor |
|
|
||||||
| a second reader | new consumer group | another queue, bound in advance | new subscription |
|
|
||||||
|
|
||||||
The last row is the one people underestimate. In Kafka and Pulsar you can add a reader that sees
|
|
||||||
history you have already processed. In RabbitMQ you cannot add one after the fact at all — the
|
|
||||||
messages are gone — so the decision to have a second consumer has to be made *before* the
|
|
||||||
messages arrive.
|
|
||||||
|
|
||||||
## What was measured, and how
|
|
||||||
|
|
||||||
Three questions, asked identically of all three brokers by driving the client libraries directly
|
|
||||||
rather than through three different Spring abstractions:
|
|
||||||
|
|
||||||
| Question | Chapter |
|
|
||||||
|---|---|
|
|
||||||
| What ordering survives when you add a second consumer? | [02](02-ordering.md) |
|
|
||||||
| Can you read the same message twice? | [03](03-replay.md) |
|
|
||||||
| How far do consumers scale, and what stops them? | [04](04-consumer-scaling.md) |
|
|
||||||
| What does each one cost to run? | [05](05-operational-footprint.md) |
|
|
||||||
|
|
||||||
Versions are the ones a Spring Boot 4.1.1 application gets: kafka-clients 4.2.1, amqp-client
|
|
||||||
5.30.0, pulsar-client 4.2.4, all read from `spring-boot-dependencies-4.1.1.pom`. The brokers are
|
|
||||||
Kafka 4.2.1, RabbitMQ 3.10.25 and Pulsar 4.2.4, each started from its own distribution by a script
|
|
||||||
in `scripts/`.
|
|
||||||
|
|
||||||
next: [Ordering](02-ordering.md)
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
prev: [Three models](01-three-models.md) · [README](../README.md) · next: [Replay](03-replay.md)
|
|
||||||
|
|
||||||
# 2. Ordering
|
|
||||||
|
|
||||||
Every broker here is FIFO with one producer and one consumer. The question that matters is what
|
|
||||||
survives the second consumer, because that is the first thing you add.
|
|
||||||
|
|
||||||
## Kafka: ordered within a partition, and a key picks the partition
|
|
||||||
|
|
||||||
Twelve records, three keys, three partitions
|
|
||||||
([`docs/output/kafka-ordering.txt`](output/kafka-ordering.txt)):
|
|
||||||
|
|
||||||
```
|
|
||||||
F -> partition [2] values [2, 5, 8, 11]
|
|
||||||
A -> partition [1] values [1, 4, 7, 10]
|
|
||||||
D -> partition [0] values [3, 6, 9, 12]
|
|
||||||
```
|
|
||||||
|
|
||||||
Each key's values come back in the order they were produced. The global sequence does not: the
|
|
||||||
consumer drains one partition's buffer before moving to the next, so the delivered order is
|
|
||||||
2, 5, 8, 11, 1, 4, 7, 10, 3, 6, 9, 12.
|
|
||||||
|
|
||||||
That is the whole Kafka ordering guarantee, and it is usually enough, because "in order" nearly
|
|
||||||
always means "in order per customer / per account / per device" rather than globally.
|
|
||||||
|
|
||||||
**A detail worth stealing.** The keys in that transcript are D, A and F, not A, B and C. With
|
|
||||||
three partitions, murmur2 sends A, B *and* C all to partition 1. Picking three obvious keys to
|
|
||||||
demonstrate partitioning would have produced a transcript in which global order was accidentally
|
|
||||||
preserved. Before you conclude that your keys spread evenly, compute
|
|
||||||
`Utils.toPositive(Utils.murmur2(key)) % partitions` for the ones you actually use.
|
|
||||||
|
|
||||||
## RabbitMQ: FIFO per queue, and no key at all
|
|
||||||
|
|
||||||
One consumer sees the queue in order. Two consumers do not
|
|
||||||
([`docs/output/rabbit-ordering.txt`](output/rabbit-ordering.txt)):
|
|
||||||
|
|
||||||
```
|
|
||||||
one queue, one consumer : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
|
|
||||||
one queue, two consumers : [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 12]
|
|
||||||
```
|
|
||||||
|
|
||||||
Message 1 went to the slower consumer and finished tenth. There is no key and no partition, so
|
|
||||||
there is nothing to pin related messages to one consumer. Ordering across related messages in
|
|
||||||
RabbitMQ means one queue and one consumer — which means no horizontal scaling of that queue —
|
|
||||||
or the consistent-hash exchange, which is a plugin and effectively reintroduces partitions by
|
|
||||||
hand.
|
|
||||||
|
|
||||||
## Pulsar: the subscription type decides, per subscriber
|
|
||||||
|
|
||||||
Two consumers on a `Shared` subscription and two on `Key_Shared`, same topic, same messages
|
|
||||||
([`docs/output/pulsar-ordering.txt`](output/pulsar-ordering.txt)):
|
|
||||||
|
|
||||||
```
|
|
||||||
Shared A -> [consumer-1, consumer-2] B -> [consumer-1, consumer-2] C -> [consumer-1, consumer-2]
|
|
||||||
Key_Shared A -> [consumer-2] B -> [consumer-1] C -> [consumer-2]
|
|
||||||
```
|
|
||||||
|
|
||||||
Under `Shared`, every key was handled by both consumers, so two messages with the same key can be
|
|
||||||
in flight at once and no ordering claim survives. Under `Key_Shared`, each key went to exactly one
|
|
||||||
consumer — Kafka's guarantee, but chosen by the subscriber rather than fixed by a partition count
|
|
||||||
someone picked when the topic was created, and recomputed as consumers join and leave.
|
|
||||||
|
|
||||||
That last property is the strongest single argument for Pulsar: two teams reading the same topic
|
|
||||||
can make different ordering-versus-throughput trades without negotiating.
|
|
||||||
|
|
||||||
next: [Replay](03-replay.md)
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
prev: [Ordering](02-ordering.md) · [README](../README.md) · next: [Consumer scaling](04-consumer-scaling.md)
|
|
||||||
|
|
||||||
# 3. Replay
|
|
||||||
|
|
||||||
"Can I read that again?" is asked after a bad deploy, and by then it is too late to change
|
|
||||||
brokers.
|
|
||||||
|
|
||||||
## Kafka
|
|
||||||
|
|
||||||
```
|
|
||||||
group replay-group-1, first read : 12 records
|
|
||||||
group replay-group-2, brand new group : 12 records
|
|
||||||
group replay-group-1, after seekToBeginning: 12 records
|
|
||||||
```
|
|
||||||
|
|
||||||
([`docs/output/kafka-replay.txt`](output/kafka-replay.txt)) Consuming moves an offset and removes
|
|
||||||
nothing. A new group, a reset offset and a `seekToBeginning` all read the same records, for as
|
|
||||||
long as retention keeps them.
|
|
||||||
|
|
||||||
## RabbitMQ
|
|
||||||
|
|
||||||
```
|
|
||||||
first drain of the queue : 12 messages
|
|
||||||
second drain of the queue : 0 messages
|
|
||||||
queue depth afterwards : 0
|
|
||||||
```
|
|
||||||
|
|
||||||
([`docs/output/rabbit-replay.txt`](output/rabbit-replay.txt)) Acknowledging deletes. There is no
|
|
||||||
offset to rewind and no second reader that can see what the first consumed. Reading a message
|
|
||||||
twice has to be arranged in advance — a second queue bound to the same exchange, or a copy written
|
|
||||||
somewhere else — and it cannot be arranged afterwards.
|
|
||||||
|
|
||||||
This is not a defect. A router that deletes what it has delivered is much cheaper to operate than
|
|
||||||
a log, and most work queues genuinely do not need history. It only becomes a defect at the moment
|
|
||||||
you need history and do not have it.
|
|
||||||
|
|
||||||
RabbitMQ streams (3.9+) are a separate, log-shaped feature that does support replay. They are a
|
|
||||||
different thing living in the same broker, with their own client protocol and their own semantics
|
|
||||||
— worth knowing about, and not what you get from `queueDeclare`.
|
|
||||||
|
|
||||||
## Pulsar
|
|
||||||
|
|
||||||
```
|
|
||||||
subscription replay-sub, first read : 12 messages
|
|
||||||
subscription replay-sub, after seek(earliest): 12 messages
|
|
||||||
subscription replay-sub-2, brand new : 12 messages
|
|
||||||
```
|
|
||||||
|
|
||||||
([`docs/output/pulsar-replay.txt`](output/pulsar-replay.txt)) `seek(MessageId)` and
|
|
||||||
`seek(timestamp)` rewind a live subscription; a new subscription starting from `Earliest` reads
|
|
||||||
everything still stored.
|
|
||||||
|
|
||||||
The difference from Kafka is the **default**, and it is the one that surprises people: Kafka keeps
|
|
||||||
a record for the retention period regardless of who read it, while Pulsar deletes a message once
|
|
||||||
every subscription has acknowledged it, unless a retention policy on the namespace says otherwise.
|
|
||||||
A Pulsar namespace with the default retention and one well-behaved subscription keeps nothing —
|
|
||||||
so the replay you are counting on requires a policy you have to set.
|
|
||||||
|
|
||||||
next: [Consumer scaling](04-consumer-scaling.md)
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
prev: [Replay](03-replay.md) · [README](../README.md) · next: [Operational footprint](05-operational-footprint.md)
|
|
||||||
|
|
||||||
# 4. Consumer scaling
|
|
||||||
|
|
||||||
The question is what happens when you add the fifth consumer.
|
|
||||||
|
|
||||||
## Kafka: partitions are a hard ceiling
|
|
||||||
|
|
||||||
Five consumers in one group on a three-partition topic
|
|
||||||
([`docs/output/kafka-consumer-scaling.txt`](output/kafka-consumer-scaling.txt)):
|
|
||||||
|
|
||||||
```
|
|
||||||
consumer-1 -> partitions [0]
|
|
||||||
consumer-2 -> partitions [1]
|
|
||||||
consumer-3 -> partitions [2]
|
|
||||||
consumer-4 -> no partitions (idle)
|
|
||||||
consumer-5 -> no partitions (idle)
|
|
||||||
```
|
|
||||||
|
|
||||||
A partition belongs to at most one consumer in a group, so partition count is the ceiling. Two of
|
|
||||||
the five processes are running, connected, healthy, and doing nothing at all — and they will keep
|
|
||||||
reporting healthy forever.
|
|
||||||
|
|
||||||
Raising the partition count later is possible and is not free: it changes which partition a key
|
|
||||||
maps to, so the per-key ordering guarantee is broken across the change for every key that moves.
|
|
||||||
In practice the partition count is a capacity decision made at design time, on incomplete
|
|
||||||
information, that you then live with.
|
|
||||||
|
|
||||||
## RabbitMQ: no ceiling, but prefetch decides whether it is real
|
|
||||||
|
|
||||||
Five consumers on one queue, forty messages
|
|
||||||
([`docs/output/rabbit-consumer-scaling.txt`](output/rabbit-consumer-scaling.txt)):
|
|
||||||
|
|
||||||
```
|
|
||||||
no basicQos at all (unlimited prefetch, the AMQP default):
|
|
||||||
consumer-1 -> 40 consumer-2..5 -> 0
|
|
||||||
|
|
||||||
basicQos(1):
|
|
||||||
consumer-1..5 -> 8 each
|
|
||||||
```
|
|
||||||
|
|
||||||
There is no structural ceiling — but with the AMQP default the broker pushes as many messages as
|
|
||||||
a consumer will accept, so the first consumer to connect can be handed the entire backlog while
|
|
||||||
four idle processes wait. `basicQos` is not a tuning knob to postpone; it is what makes the
|
|
||||||
fan-out exist.
|
|
||||||
|
|
||||||
Spring AMQP sets it for you: `AbstractMessageListenerContainer.DEFAULT_PREFETCH_COUNT` is 250.
|
|
||||||
Better than unlimited, and still enough to concentrate any backlog smaller than 250 messages on
|
|
||||||
one consumer.
|
|
||||||
|
|
||||||
## Pulsar: no ceiling either, and the same trap under a different name
|
|
||||||
|
|
||||||
Five consumers, one *non-partitioned* topic, forty messages
|
|
||||||
([`docs/output/pulsar-consumer-scaling.txt`](output/pulsar-consumer-scaling.txt)):
|
|
||||||
|
|
||||||
```
|
|
||||||
receiverQueueSize default (1000):
|
|
||||||
one or two consumers take everything; the rest receive nothing
|
|
||||||
|
|
||||||
receiverQueueSize(1):
|
|
||||||
consumer-1..5 -> 8 each
|
|
||||||
```
|
|
||||||
|
|
||||||
The topic has no partitions and five consumers still share the work, which in Kafka would require
|
|
||||||
at least five partitions decided in advance. But the default receiver queue is a thousand
|
|
||||||
messages, so the first consumers to connect pull the whole backlog into their own buffers first.
|
|
||||||
Same failure as RabbitMQ's unlimited prefetch, four times the default.
|
|
||||||
|
|
||||||
## The shape of the answer
|
|
||||||
|
|
||||||
- Kafka gives you ordering per key and pays for it with a fixed parallelism ceiling.
|
|
||||||
- RabbitMQ gives you unlimited competing consumers and pays for it with no ordering across them.
|
|
||||||
- Pulsar lets each subscription choose, which is genuinely the best of both — at the operational
|
|
||||||
cost measured in [the next chapter](05-operational-footprint.md).
|
|
||||||
|
|
||||||
And all three brokers have a client-side buffer that will quietly defeat your fan-out if you leave
|
|
||||||
it at the default and your backlog is small. That is the one finding here that applies to
|
|
||||||
whichever you pick.
|
|
||||||
|
|
||||||
next: [Operational footprint](05-operational-footprint.md)
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
prev: [Consumer scaling](04-consumer-scaling.md) · [README](../README.md) · next: [What Spring adds](06-what-spring-adds.md)
|
|
||||||
|
|
||||||
# 5. Operational footprint
|
|
||||||
|
|
||||||
"Ops burden" cannot be benchmarked. The number of moving parts, the memory floor and the size of
|
|
||||||
the configuration surface can be, and they are what people are actually asking about.
|
|
||||||
|
|
||||||
Each broker started from its shipped distribution with default configuration and a 700 MB heap
|
|
||||||
cap, on one 2-core / 3.8 GB Linux box, Temurin JDK 21
|
|
||||||
([`docs/output/footprint.txt`](output/footprint.txt)):
|
|
||||||
|
|
||||||
| | Kafka 4.2.1 | RabbitMQ 3.10.25 | Pulsar 4.2.4 standalone |
|
|
||||||
|---|---|---|---|
|
|
||||||
| launch to first accepted connection | 10.0 s | 15.1 s | 20.8 s |
|
|
||||||
| resident memory at idle | 333 MB | 115 MB | 610 MB |
|
|
||||||
| server processes | 1 | 1 (+ `epmd`) | 1 |
|
|
||||||
| listening ports | 9092, 9093 | 5672, 4369, 25672 | 6650, 8080, 2181 |
|
|
||||||
| unpacked distribution | 135 MB | 26 MB | 344 MB |
|
|
||||||
| settings in the shipped default config | 24 | **0** | 357 |
|
|
||||||
|
|
||||||
Read those numbers as orders of magnitude, not as a benchmark: one sample, one small machine.
|
|
||||||
|
|
||||||
Three things they say clearly.
|
|
||||||
|
|
||||||
**RabbitMQ ships no configuration file at all.** The boot log records `Config file(s): (none)`;
|
|
||||||
`rabbitmq.conf.example` is entirely commented out. Everything works out of the box, and the
|
|
||||||
smallest resident footprint here is the one that is not a JVM. Against that, `epmd` on 4369 and
|
|
||||||
the inter-node port on 25672 are the Erlang distribution, which is also how clustering works and
|
|
||||||
how clustering goes wrong.
|
|
||||||
|
|
||||||
**Pulsar standalone is three systems in one process.** Port 2181 is ZooKeeper and the on-disk
|
|
||||||
data is BookKeeper's; the standalone distribution hides that behind one command. A real
|
|
||||||
deployment does not: you operate ZooKeeper (or, from Pulsar 3.x, an alternative metadata store),
|
|
||||||
BookKeeper bookies and Pulsar brokers as three tiers with three scaling stories. The 357-setting
|
|
||||||
`standalone.conf` is the honest signal here — that is the configuration surface, and running it
|
|
||||||
seriously means learning most of it.
|
|
||||||
|
|
||||||
**Kafka since KRaft is genuinely simpler than it was.** One process, two ports, 24 settings, no
|
|
||||||
ZooKeeper. The old "Kafka means also running ZooKeeper" objection is a version behind; anyone
|
|
||||||
comparing on that basis is comparing to 2022.
|
|
||||||
|
|
||||||
## What the numbers do not include
|
|
||||||
|
|
||||||
The footprint above is one node at idle. The thing that actually determines ops burden is what
|
|
||||||
happens at three in the morning:
|
|
||||||
|
|
||||||
- **Kafka**: rebalances, consumer lag as the primary signal, partition-count decisions you cannot
|
|
||||||
cleanly reverse, and a broad ecosystem of tools that assume Kafka.
|
|
||||||
- **RabbitMQ**: the management plugin is genuinely good, queue depth is a direct and obvious
|
|
||||||
signal, and the hard problem is network partitions in a cluster — which the Erlang distribution
|
|
||||||
makes fast to detect and awkward to resolve.
|
|
||||||
- **Pulsar**: the fewest people on your team will have run it. That is not a technical property
|
|
||||||
and it is usually the deciding one.
|
|
||||||
|
|
||||||
next: [What Spring adds](06-what-spring-adds.md)
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
prev: [Operational footprint](05-operational-footprint.md) · [README](../README.md) · next: [The decision table](07-the-decision-table.md)
|
|
||||||
|
|
||||||
# 6. What Spring adds, and what Boot 4 no longer gives you for free
|
|
||||||
|
|
||||||
The measurements in this module drive the client libraries directly, so that what is being
|
|
||||||
compared is the brokers rather than three sets of Spring defaults. In an application you would use
|
|
||||||
the Spring integrations, and they are not equivalent to one another.
|
|
||||||
|
|
||||||
| | Kafka | RabbitMQ | Pulsar |
|
|
||||||
|---|---|---|---|
|
|
||||||
| project | Spring for Apache Kafka 4.1.1 | Spring AMQP 4.1.1 | Spring for Apache Pulsar 2.0.7 |
|
|
||||||
| starter | `spring-boot-starter-kafka` | `spring-boot-starter-amqp` | `spring-boot-starter-pulsar` |
|
|
||||||
| listener | `@KafkaListener` | `@RabbitListener` | `@PulsarListener` |
|
|
||||||
| template | `KafkaTemplate` | `RabbitTemplate` | `PulsarTemplate` |
|
|
||||||
| retry / DLQ | `DefaultErrorHandler`, `@RetryableTopic` | dead-letter exchange, container error handler | `DeadLetterPolicy` on the listener |
|
|
||||||
|
|
||||||
All three are Boot-managed at 4.1.1, so you do not pin their versions.
|
|
||||||
|
|
||||||
## The Boot 4 trap that applies to all three
|
|
||||||
|
|
||||||
**In Spring Boot 4, depending on a messaging library directly rather than through its Boot starter
|
|
||||||
means you have no auto-configuration.** The auto-configuration classes moved out of
|
|
||||||
`spring-boot-autoconfigure` into per-technology modules that only the starters bring:
|
|
||||||
|
|
||||||
| depending on | what you lose | how it presents |
|
|
||||||
|---|---|---|
|
|
||||||
| `org.springframework.kafka:spring-kafka` | `spring-boot-kafka` | `No qualifying bean of type KafkaTemplate<...>` — the context starts fine |
|
|
||||||
| `org.springframework.amqp:spring-rabbit` | `spring-boot-amqp` | no `RabbitTemplate`, no `RabbitAdmin` |
|
|
||||||
| `org.springframework.pulsar:spring-pulsar` | `spring-boot-pulsar` | no `PulsarTemplate` |
|
|
||||||
|
|
||||||
Every Boot 3 tutorial gets this wrong now, and the symptom is a missing bean rather than anything
|
|
||||||
that names the cause. Use the starters.
|
|
||||||
|
|
||||||
## The Jackson fork, in both Kafka and RabbitMQ
|
|
||||||
|
|
||||||
Boot 4 moved to Jackson 3 (`tools.jackson`), and both messaging projects ship converters for
|
|
||||||
both generations. **A `2` in the class name means the previous Jackson** — which is the opposite
|
|
||||||
of the convention you would guess:
|
|
||||||
|
|
||||||
- Spring Kafka: `JsonSerializer`/`JsonDeserializer` are Jackson 2; `JacksonJsonSerializer`,
|
|
||||||
`JacksonJsonDeserializer` and `JacksonJsonSerde` are Jackson 3.
|
|
||||||
- Spring AMQP: `Jackson2JsonMessageConverter` is Jackson 2; `JacksonJsonMessageConverter` is
|
|
||||||
Jackson 3.
|
|
||||||
|
|
||||||
Picking the wrong one gives you `SerializationException: Can't serialize data`, whose cause is
|
|
||||||
`Java 8 date/time type java.time.Instant not supported by default` — a message about date types
|
|
||||||
for what is really a wrong-library problem.
|
|
||||||
|
|
||||||
The [kafka-basics](../kafka-basics/README.md) and [rabbitmq](../rabbitmq/README.md) modules in
|
|
||||||
this repository cover both stacks in detail.
|
|
||||||
|
|
||||||
next: [The decision table](07-the-decision-table.md)
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
prev: [What Spring adds](06-what-spring-adds.md) · [README](../README.md)
|
|
||||||
|
|
||||||
# 7. The decision table
|
|
||||||
|
|
||||||
Every row below is either a measurement in `docs/output/` or a statement about operating the
|
|
||||||
thing. Nothing here is a vendor claim.
|
|
||||||
|
|
||||||
| | Kafka 4.2.1 | RabbitMQ 3.10.25 | Pulsar 4.2.4 |
|
|
||||||
|---|---|---|---|
|
|
||||||
| ordering with one consumer | FIFO per partition | FIFO per queue | FIFO |
|
|
||||||
| ordering with many consumers | per key, always | **none** | per key with `Key_Shared`, none with `Shared` |
|
|
||||||
| who chooses that | topic design | plugin, or one consumer | each subscription, independently |
|
|
||||||
| replay after the fact | yes, within retention | **no** | yes, if retention is configured |
|
|
||||||
| second independent reader | new consumer group, any time | must be arranged in advance | new subscription, any time |
|
|
||||||
| consumer parallelism ceiling | partition count | none | none |
|
|
||||||
| changing that ceiling | repartition; breaks key→partition | nothing to change | nothing to change |
|
|
||||||
| the client-side trap | none by default | unlimited prefetch (Spring: 250) | `receiverQueueSize` 1000 |
|
|
||||||
| memory at idle | 333 MB | **115 MB** | 610 MB |
|
|
||||||
| processes to operate | 1 (KRaft) | 1 + `epmd` | broker + BookKeeper + metadata store |
|
|
||||||
| shipped default settings | 24 | **0** | 357 |
|
|
||||||
| Spring project maturity | very high | very high | good, much smaller community |
|
|
||||||
|
|
||||||
## Choosing
|
|
||||||
|
|
||||||
**Choose RabbitMQ** when the work is a queue of tasks: each message is an instruction, order
|
|
||||||
between instructions does not matter, and once it is done it is done. It is the smallest thing
|
|
||||||
that works, it has the best out-of-the-box operability of the three, and queue depth is a metric
|
|
||||||
anyone can interpret. Choose it in the knowledge that you are giving up replay permanently —
|
|
||||||
adding it later is a broker migration, not a configuration change.
|
|
||||||
|
|
||||||
**Choose Kafka** when the messages are events other people will want to read: when more than one
|
|
||||||
consumer will exist, when someone will need to reprocess history after a bug, or when ordering per
|
|
||||||
entity is part of the contract. Pay for it with a partition count decided too early, consumers
|
|
||||||
that scale only as far as that number, and an operational model where lag is the thing you watch.
|
|
||||||
KRaft has removed the old ZooKeeper objection.
|
|
||||||
|
|
||||||
**Choose Pulsar** when you genuinely need what neither of the others gives you: per-subscription
|
|
||||||
choice of ordering versus fan-out, consumer counts not bounded by a number chosen at topic
|
|
||||||
creation, or multi-tenancy with real isolation. It is the most capable design here. It is also
|
|
||||||
three systems, 357 settings, five times RabbitMQ's memory floor, and the one your team has least
|
|
||||||
experience with — and that last point decides more incidents than the first three prevent.
|
|
||||||
|
|
||||||
**If the honest answer is "we do not know yet"**, that argues for Kafka, on grounds that have
|
|
||||||
nothing to do with the technology: you can hire for it, your monitoring vendor supports it, and
|
|
||||||
the failure modes are documented by thousands of people who hit them first. That is a real
|
|
||||||
engineering argument and it is fine to make it out loud.
|
|
||||||
|
|
||||||
## The question that dissolves the choice
|
|
||||||
|
|
||||||
A surprising number of these decisions are made for a system that has one producer, one consumer
|
|
||||||
and fewer than a hundred messages a second. At that volume all three brokers work, none of the
|
|
||||||
measurements above will ever be reached, and the decision is entirely about what your team can
|
|
||||||
operate at three in the morning.
|
|
||||||
|
|
||||||
The measurements matter when you can name which row you are relying on. If you cannot, you are
|
|
||||||
picking an operational burden, not a broker — and the cheapest one to operate is the one in the
|
|
||||||
`115 MB` cell.
|
|
||||||
|
|
||||||
[README](../README.md)
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
== Operational footprint, measured on one 2-core / 3.8 GB Linux box ==
|
|
||||||
|
|
||||||
Each broker started from its shipped distribution with default configuration and a
|
|
||||||
700 MB heap cap, on Temurin JDK 21. Times are one sample on a small box: treat them as
|
|
||||||
orders of magnitude, not as a benchmark.
|
|
||||||
|
|
||||||
broker : kafka
|
|
||||||
time from launch to first
|
|
||||||
accepted connection : 10035 ms
|
|
||||||
resident memory at idle : 333 MB
|
|
||||||
server processes : 1
|
|
||||||
listening ports : 9092 (broker), 9093 (controller)
|
|
||||||
unpacked distribution size : 135 MB
|
|
||||||
settings in shipped default
|
|
||||||
configuration file : 24 (server.properties)
|
|
||||||
|
|
||||||
broker : rabbit
|
|
||||||
time from launch to first
|
|
||||||
accepted connection : 15053 ms
|
|
||||||
resident memory at idle : 115 MB
|
|
||||||
server processes : 1
|
|
||||||
listening ports : 5672 (AMQP), 4369 (epmd), 25672 (inter-node)
|
|
||||||
unpacked distribution size : 26 MB
|
|
||||||
settings in shipped default
|
|
||||||
configuration file : 0 (rabbitmq.conf.example)
|
|
||||||
epmd processes : 1
|
|
||||||
NOTE: RabbitMQ ships no configuration file at all. rabbitmq.conf.example is
|
|
||||||
entirely commented out and the boot log records "Config file(s): (none)".
|
|
||||||
Everything in that file is documentation, not a default.
|
|
||||||
|
|
||||||
broker : pulsar
|
|
||||||
time from launch to first
|
|
||||||
accepted connection : 20801 ms
|
|
||||||
resident memory at idle : 610 MB
|
|
||||||
server processes : 1
|
|
||||||
listening ports : 6650 (binary), 8080 (admin/REST), 2181 (ZooKeeper)
|
|
||||||
unpacked distribution size : 344 MB
|
|
||||||
settings in shipped default
|
|
||||||
configuration file : 357 (standalone.conf)
|
|
||||||
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
== Kafka: partitions are the ceiling on consumer parallelism ==
|
|
||||||
|
|
||||||
topic 'orders-scaling', 3 partitions, 5 consumers in one group
|
|
||||||
|
|
||||||
consumer-1 -> partitions [0]
|
|
||||||
consumer-2 -> partitions [1]
|
|
||||||
consumer-3 -> partitions [2]
|
|
||||||
consumer-4 -> no partitions (idle)
|
|
||||||
consumer-5 -> no partitions (idle)
|
|
||||||
|
|
||||||
consumers with no partitions: 2
|
|
||||||
|
|
||||||
A partition is assigned to at most one consumer in a group, so the number
|
|
||||||
of partitions is a hard ceiling on consumer parallelism. Adding consumers
|
|
||||||
beyond it adds idle processes, not throughput.
|
|
||||||
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
== Kafka: ordering is per partition ==
|
|
||||||
|
|
||||||
produced 12 records, keys D/A/F round-robin, values 1..12 in order
|
|
||||||
(keys chosen so that murmur2 spreads them: D->0, A->1, F->2. A, B and C
|
|
||||||
all hash to partition 1 with three partitions, which is worth knowing
|
|
||||||
before you decide your keys are well distributed.)
|
|
||||||
|
|
||||||
consumed in this order:
|
|
||||||
F=2@p2
|
|
||||||
F=5@p2
|
|
||||||
F=8@p2
|
|
||||||
F=11@p2
|
|
||||||
A=1@p1
|
|
||||||
A=4@p1
|
|
||||||
A=7@p1
|
|
||||||
A=10@p1
|
|
||||||
D=3@p0
|
|
||||||
D=6@p0
|
|
||||||
D=9@p0
|
|
||||||
D=12@p0
|
|
||||||
|
|
||||||
per key:
|
|
||||||
F -> partition [2] values [2, 5, 8, 11]
|
|
||||||
A -> partition [1] values [1, 4, 7, 10]
|
|
||||||
D -> partition [0] values [3, 6, 9, 12]
|
|
||||||
|
|
||||||
Order is preserved within each key because a key hashes to one partition.
|
|
||||||
Across keys it is not: the values above are not 1..12 in order, because a
|
|
||||||
consumer drains one partition's buffer before the next.
|
|
||||||
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
== Kafka: the log is the storage ==
|
|
||||||
|
|
||||||
group replay-group-1, first read : 12 records
|
|
||||||
group replay-group-2, brand new group : 12 records
|
|
||||||
group replay-group-1, after seekToBeginning: 12 records
|
|
||||||
|
|
||||||
Consuming does not remove anything. A consumer group is a cursor over a log
|
|
||||||
that the broker keeps until retention expires, so a new group, a reset
|
|
||||||
offset or a seek all read the same records again.
|
|
||||||
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
== Pulsar: no partition ceiling, but the receiver queue decides who gets the work ==
|
|
||||||
|
|
||||||
one non-partitioned topic, 40 messages, 5 consumers, Shared subscription
|
|
||||||
|
|
||||||
receiverQueueSize left at the default (1000):
|
|
||||||
consumer-1 -> 40 messages
|
|
||||||
consumer-2 -> 0 messages
|
|
||||||
consumer-3 -> 0 messages
|
|
||||||
consumer-4 -> 0 messages
|
|
||||||
consumer-5 -> 0 messages
|
|
||||||
consumers that received nothing : 4
|
|
||||||
|
|
||||||
receiverQueueSize(1):
|
|
||||||
consumer-1 -> 8 messages
|
|
||||||
consumer-2 -> 8 messages
|
|
||||||
consumer-3 -> 8 messages
|
|
||||||
consumer-4 -> 8 messages
|
|
||||||
consumer-5 -> 8 messages
|
|
||||||
consumers that received nothing : 0
|
|
||||||
|
|
||||||
The topic has no partitions and five consumers can still share the work --
|
|
||||||
in Kafka the same shape needs at least five partitions, chosen when the
|
|
||||||
topic was created. But the default receiver queue is 1000 messages, so the
|
|
||||||
first consumers to connect pull the whole 40-message backlog into their own
|
|
||||||
buffers before the rest ask for anything, and the subscription looks
|
|
||||||
broken. Which consumers win is a race and varies between runs -- one
|
|
||||||
consumer taking all forty, or two taking twenty each -- but the consumers
|
|
||||||
that lose it see nothing at all. This is the same trap as RabbitMQ's
|
|
||||||
unbounded prefetch, with a different name and a much larger default.
|
|
||||||
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
== Pulsar: the subscription type decides ==
|
|
||||||
|
|
||||||
12 messages, keys A/B/C, values 1..12 in order, two consumers per
|
|
||||||
subscription, receiverQueueSize 1 so the first consumer cannot take the
|
|
||||||
whole backlog.
|
|
||||||
|
|
||||||
Shared subscription, which consumers saw each key:
|
|
||||||
A -> [consumer-1, consumer-2]
|
|
||||||
B -> [consumer-1, consumer-2]
|
|
||||||
C -> [consumer-1, consumer-2]
|
|
||||||
|
|
||||||
Key_Shared subscription, which consumers saw each key:
|
|
||||||
A -> [consumer-1]
|
|
||||||
B -> [consumer-1]
|
|
||||||
C -> [consumer-1]
|
|
||||||
|
|
||||||
A Shared subscription round-robins individual messages, so messages with
|
|
||||||
the same key end up on different consumers and can be processed at the
|
|
||||||
same time: there is no per-key order left to speak of. Key_Shared hashes
|
|
||||||
the key to one consumer, which is Kafka's guarantee -- except that the
|
|
||||||
assignment belongs to the subscription and is recomputed as consumers come
|
|
||||||
and go, rather than being fixed by a partition count chosen when the topic
|
|
||||||
was created.
|
|
||||||
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
== Pulsar: acknowledged, but still there ==
|
|
||||||
|
|
||||||
subscription replay-sub, first read : 12 messages
|
|
||||||
subscription replay-sub, after seek(earliest): 12 messages
|
|
||||||
subscription replay-sub-2, brand new : 12 messages
|
|
||||||
|
|
||||||
Acknowledgement moves a cursor; the message itself lives in the managed
|
|
||||||
ledger. seek(MessageId) and seek(timestamp) rewind a live subscription,
|
|
||||||
which Kafka can also do by resetting offsets. What differs is the default:
|
|
||||||
Pulsar deletes a message once every subscription has acknowledged it,
|
|
||||||
unless a retention policy on the namespace says otherwise, whereas Kafka
|
|
||||||
keeps it for the retention period regardless of who read it. A Pulsar
|
|
||||||
topic with no retention policy and no subscriptions keeps nothing.
|
|
||||||
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
== RabbitMQ: consumers scale, and prefetch decides whether they actually do ==
|
|
||||||
|
|
||||||
one queue, 40 messages, 5 consumers, each taking 10 ms per message
|
|
||||||
|
|
||||||
no basicQos at all (unlimited prefetch, the AMQP default):
|
|
||||||
consumer-1 -> 40 messages
|
|
||||||
consumer-2 -> 0 messages
|
|
||||||
consumer-3 -> 0 messages
|
|
||||||
consumer-4 -> 0 messages
|
|
||||||
consumer-5 -> 0 messages
|
|
||||||
consumers that received nothing : 4
|
|
||||||
|
|
||||||
basicQos(1):
|
|
||||||
consumer-1 -> 8 messages
|
|
||||||
consumer-2 -> 9 messages
|
|
||||||
consumer-3 -> 8 messages
|
|
||||||
consumer-4 -> 8 messages
|
|
||||||
consumer-5 -> 7 messages
|
|
||||||
consumers that received nothing : 0
|
|
||||||
|
|
||||||
Every consumer on a queue competes for the same messages, so adding
|
|
||||||
consumers adds throughput and there is no structural ceiling of the kind
|
|
||||||
Kafka's partition count imposes. But with the AMQP default the broker
|
|
||||||
pushes as many messages as a consumer will take, so whichever consumer
|
|
||||||
connects first can be handed the entire backlog while the others sit idle.
|
|
||||||
basicQos is not a tuning knob you get to postpone; it is what makes the
|
|
||||||
fan-out real. Spring AMQP sets it for you --
|
|
||||||
AbstractMessageListenerContainer.DEFAULT_PREFETCH_COUNT is 250 -- which is
|
|
||||||
better than unlimited and still large enough to concentrate a small
|
|
||||||
backlog on one consumer.
|
|
||||||
|
|
||||||
The price of all this is the ordering measurement: there is no key, so
|
|
||||||
nothing constrains related messages to one consumer.
|
|
||||||
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
== RabbitMQ: FIFO per queue, per consumer ==
|
|
||||||
|
|
||||||
one queue, one consumer, 12 messages
|
|
||||||
completion order : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
|
|
||||||
|
|
||||||
one queue, two consumers, prefetch 1, consumer-1 slower than consumer-2
|
|
||||||
completion order : [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 12]
|
|
||||||
out-of-order steps: 1
|
|
||||||
|
|
||||||
A queue is FIFO and a single consumer sees it that way. The moment a second
|
|
||||||
consumer is added the broker hands the next message to whichever consumer
|
|
||||||
is free, so the order in which work finishes is no longer the order in
|
|
||||||
which it was published. There is no key: RabbitMQ has no notion of a
|
|
||||||
partition to which related messages could be pinned. Ordering across
|
|
||||||
related messages means one queue and one consumer, and therefore no
|
|
||||||
horizontal scaling for that queue -- or a consistent-hash exchange, which
|
|
||||||
is a plugin.
|
|
||||||
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
== RabbitMQ: there is nothing to replay ==
|
|
||||||
|
|
||||||
first drain of the queue : 12 messages
|
|
||||||
second drain of the queue : 0 messages
|
|
||||||
queue depth afterwards : 0
|
|
||||||
|
|
||||||
Acknowledging a message deletes it. The broker is a router with buffers,
|
|
||||||
not a log: there is no offset to rewind and no second reader that can see
|
|
||||||
what the first one consumed. Reading the same message twice means
|
|
||||||
arranging it in advance -- a second queue bound to the same exchange, or a
|
|
||||||
copy written somewhere else -- and it cannot be arranged after the fact.
|
|
||||||
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
[INFO] Running com.ankurm.brokers.KafkaComparisonTest
|
|
||||||
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 26.88 s -- in com.ankurm.brokers.KafkaComparisonTest
|
|
||||||
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
|
|
||||||
[INFO] BUILD SUCCESS
|
|
||||||
[INFO] Running com.ankurm.brokers.RabbitComparisonTest
|
|
||||||
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.732 s -- in com.ankurm.brokers.RabbitComparisonTest
|
|
||||||
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
|
|
||||||
[INFO] BUILD SUCCESS
|
|
||||||
[INFO] Running com.ankurm.brokers.PulsarComparisonTest
|
|
||||||
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 55.00 s -- in com.ankurm.brokers.PulsarComparisonTest
|
|
||||||
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
|
|
||||||
[INFO] BUILD SUCCESS
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
|
|
||||||
<!-- Every client version below is managed by spring-boot-dependencies 4.1.1, so the three
|
|
||||||
brokers are compared at the versions a Boot 4.1 application would actually get:
|
|
||||||
kafka-clients 4.2.1, amqp-client 5.30.0, pulsar-client 4.2.4. Read from
|
|
||||||
spring-boot-dependencies-4.1.1.pom, not from release announcements. -->
|
|
||||||
<parent>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
|
||||||
<version>4.1.1</version>
|
|
||||||
<relativePath/>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<groupId>com.ankurm</groupId>
|
|
||||||
<artifactId>broker-comparison</artifactId>
|
|
||||||
<version>1.0</version>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<java.version>25</java.version>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter</artifactId>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<!-- The three client libraries, driven directly. The comparison is between the brokers'
|
|
||||||
delivery models, and going through three different Spring abstractions would put three
|
|
||||||
different sets of defaults between the measurement and the thing being measured.
|
|
||||||
What each Boot starter adds on top is covered in docs/06-what-spring-adds.md. -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.kafka</groupId>
|
|
||||||
<artifactId>kafka-clients</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.rabbitmq</groupId>
|
|
||||||
<artifactId>amqp-client</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.pulsar</groupId>
|
|
||||||
<artifactId>pulsar-client</artifactId>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<!-- Provides the in-process KRaft broker used by the Kafka measurements: a real Kafka
|
|
||||||
broker, no Docker. -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.kafka</groupId>
|
|
||||||
<artifactId>spring-kafka-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<!-- Each broker is started by its own script and the matching tagged tests are run on
|
|
||||||
their own; see scripts/run-all.sh, which passes -Dgroups=kafka|rabbit|pulsar. Running
|
|
||||||
"mvn test" with no group runs all three and needs all three brokers up. -->
|
|
||||||
|
|
||||||
</project>
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Measures the operational footprint of one broker: how long it takes to accept a connection,
|
|
||||||
# how much memory it holds at idle, how many processes and listening ports it opens, and how
|
|
||||||
# large its shipped default configuration is.
|
|
||||||
#
|
|
||||||
# These are proxies, not a benchmark. "Ops burden" is not directly measurable, but the number of
|
|
||||||
# moving parts, the memory floor and the size of the configuration surface are, and they are what
|
|
||||||
# people are actually asking about when they ask which broker is heavier to run.
|
|
||||||
#
|
|
||||||
# scripts/footprint.sh kafka|rabbit|pulsar
|
|
||||||
set -euo pipefail
|
|
||||||
BROKER="${1:?kafka|rabbit|pulsar}"
|
|
||||||
|
|
||||||
extra=""
|
|
||||||
port_open() { (echo > "/dev/tcp/127.0.0.1/$1") 2>/dev/null; }
|
|
||||||
rss_mb() { ps -eo rss,cmd | grep -F "$1" | grep -v grep | awk '{s+=$1} END {printf "%.0f", s/1024}'; }
|
|
||||||
procs() { ps -eo cmd | grep -F "$1" | grep -cv grep; }
|
|
||||||
settings() { grep -cE '^[a-zA-Z]' "$1" 2>/dev/null || echo 0; }
|
|
||||||
|
|
||||||
start=$(date +%s%3N)
|
|
||||||
case "$BROKER" in
|
|
||||||
kafka)
|
|
||||||
: "${KAFKA_HOME:?set KAFKA_HOME}"
|
|
||||||
# Wipe whatever log.dirs points at, so the format below is not refused with
|
|
||||||
# "Invalid cluster.id ... Expected X, but read Y" from a previous run.
|
|
||||||
KAFKA_LOG_DIRS=$(grep -E '^log.dirs=' "$KAFKA_HOME/config/server.properties" | cut -d= -f2)
|
|
||||||
rm -rf ${KAFKA_LOG_DIRS//,/ }
|
|
||||||
"$KAFKA_HOME/bin/kafka-storage.sh" format --standalone -t "$("$KAFKA_HOME/bin/kafka-storage.sh" random-uuid)" \
|
|
||||||
-c "$KAFKA_HOME/config/server.properties" --ignore-formatted >/dev/null
|
|
||||||
start=$(date +%s%3N) # after formatting: kafka-storage.sh is two more JVM starts and is a
|
|
||||||
# one-off, not part of what a restart costs
|
|
||||||
setsid nohup "$KAFKA_HOME/bin/kafka-server-start.sh" "$KAFKA_HOME/config/server.properties" \
|
|
||||||
> /tmp/kafka-start.log 2>&1 < /dev/null &
|
|
||||||
for _ in $(seq 1 90); do port_open 9092 && break; sleep 1; done
|
|
||||||
ready=$(( $(date +%s%3N) - start ))
|
|
||||||
marker="kafka.Kafka"; ports="9092 (broker), 9093 (controller)"; conf="$KAFKA_HOME/config/server.properties"
|
|
||||||
dist="$KAFKA_HOME"
|
|
||||||
;;
|
|
||||||
rabbit)
|
|
||||||
: "${RABBITMQ_HOME:?set RABBITMQ_HOME}"; : "${ERL_ROOT:?set ERL_ROOT}"
|
|
||||||
scripts/rabbit-broker.sh >/dev/null
|
|
||||||
ready=$(( $(date +%s%3N) - start ))
|
|
||||||
# The broker is an Erlang VM, so the process to measure is beam.smp, not anything named
|
|
||||||
# "rabbitmq". epmd is a second, tiny process and is counted separately below.
|
|
||||||
marker="beam.smp"; ports="5672 (AMQP), 4369 (epmd), 25672 (inter-node)"
|
|
||||||
conf="$RABBITMQ_HOME/etc/rabbitmq/rabbitmq.conf.example"; dist="$RABBITMQ_HOME"
|
|
||||||
extra="epmd processes : $(procs epmd)
|
|
||||||
NOTE: RabbitMQ ships no configuration file at all. rabbitmq.conf.example is
|
|
||||||
entirely commented out and the boot log records \"Config file(s): (none)\".
|
|
||||||
Everything in that file is documentation, not a default."
|
|
||||||
;;
|
|
||||||
pulsar)
|
|
||||||
: "${PULSAR_HOME:?set PULSAR_HOME}"
|
|
||||||
scripts/pulsar-broker.sh >/dev/null
|
|
||||||
ready=$(( $(date +%s%3N) - start ))
|
|
||||||
marker="PulsarStandaloneStarter"; ports="6650 (binary), 8080 (admin/REST), 2181 (ZooKeeper)"
|
|
||||||
conf="$PULSAR_HOME/conf/standalone.conf"; dist="$PULSAR_HOME"
|
|
||||||
;;
|
|
||||||
*) echo "unknown broker $BROKER" >&2; exit 2 ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
cat <<EOF
|
|
||||||
broker : $BROKER
|
|
||||||
time from launch to first
|
|
||||||
accepted connection : ${ready} ms
|
|
||||||
resident memory at idle : $(rss_mb "$marker") MB
|
|
||||||
server processes : $(procs "$marker")
|
|
||||||
listening ports : $ports
|
|
||||||
unpacked distribution size : $(du -sm "$dist" | cut -f1) MB
|
|
||||||
settings in shipped default
|
|
||||||
configuration file : $(settings "$conf") ($(basename "$conf"))
|
|
||||||
${extra:-}
|
|
||||||
EOF
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Start a real Apache Pulsar broker with no Docker and no root.
|
|
||||||
#
|
|
||||||
# The standalone distribution bundles ZooKeeper, BookKeeper and the broker in one process, which
|
|
||||||
# is why a single tarball is enough. -nss skips the stream storage (BookKeeper's table service,
|
|
||||||
# needed only by stateful Pulsar Functions) and -nfw skips the functions worker; both save
|
|
||||||
# several hundred megabytes of heap and a few seconds of startup.
|
|
||||||
#
|
|
||||||
# PULSAR_HOME must point at an unpacked apache-pulsar-<version>-bin directory. Pulsar 4.2
|
|
||||||
# supports Java 17 and 21; the transcripts here were produced on Temurin 21.
|
|
||||||
set -eu
|
|
||||||
: "${PULSAR_HOME:?set PULSAR_HOME to an unpacked apache-pulsar-*-bin directory}"
|
|
||||||
export PULSAR_MEM="${PULSAR_MEM:--Xms384m -Xmx700m -XX:MaxDirectMemorySize=384m}"
|
|
||||||
|
|
||||||
cd "$PULSAR_HOME"
|
|
||||||
setsid nohup bin/pulsar standalone -nss -nfw > /tmp/pulsar-start.log 2>&1 < /dev/null &
|
|
||||||
for _ in $(seq 1 90); do
|
|
||||||
if [ "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/admin/v2/brokers/version)" = "200" ]; then
|
|
||||||
echo "broker ready on 6650 (admin 8080), version $(curl -s http://127.0.0.1:8080/admin/v2/brokers/version)"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
echo "broker did not start; see /tmp/pulsar-start.log" >&2
|
|
||||||
exit 1
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Start a real RabbitMQ broker with no Docker and no root.
|
|
||||||
#
|
|
||||||
# RabbitMQ is an Erlang application, so an Erlang runtime and epmd on the path are the whole
|
|
||||||
# dependency. Point ERL_ROOT at an Erlang installation and RABBITMQ_HOME at an unpacked
|
|
||||||
# rabbitmq-server-generic-unix tarball. Ubuntu 22.04 ships Erlang 24, whose newest compatible
|
|
||||||
# broker is 3.10.25; 3.11 and later need Erlang 25.
|
|
||||||
#
|
|
||||||
# The one non-obvious step is starting epmd yourself: rabbitmq-server's own attempt to start it
|
|
||||||
# fails in a container without a resolvable hostname, and the failure surfaces as a forty-line
|
|
||||||
# Erlang crash dump ending in {'EXIT',nodistribution}.
|
|
||||||
set -eu
|
|
||||||
: "${ERL_ROOT:?set ERL_ROOT to an Erlang installation directory}"
|
|
||||||
: "${RABBITMQ_HOME:?set RABBITMQ_HOME to an unpacked rabbitmq-server-generic-unix directory}"
|
|
||||||
|
|
||||||
export PATH="$ERL_ROOT/bin:$ERL_ROOT/erts-"*/bin":$PATH"
|
|
||||||
export RABBITMQ_MNESIA_BASE="${RABBITMQ_MNESIA_BASE:-/tmp/rmq/data}"
|
|
||||||
export RABBITMQ_LOG_BASE="${RABBITMQ_LOG_BASE:-/tmp/rmq/log}"
|
|
||||||
export RABBITMQ_NODENAME="${RABBITMQ_NODENAME:-rabbit@localhost}"
|
|
||||||
export HOME="${HOME:-/tmp/rmq}"
|
|
||||||
mkdir -p "$RABBITMQ_MNESIA_BASE" "$RABBITMQ_LOG_BASE"
|
|
||||||
|
|
||||||
epmd -daemon 2>/dev/null || true
|
|
||||||
sleep 1
|
|
||||||
setsid nohup "$RABBITMQ_HOME/sbin/rabbitmq-server" > /tmp/rmq/boot.log 2>&1 < /dev/null &
|
|
||||||
for _ in $(seq 1 60); do
|
|
||||||
if (echo > /dev/tcp/127.0.0.1/5672) 2>/dev/null; then echo "broker ready on 5672"; exit 0; fi
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
echo "broker did not start; see /tmp/rmq/boot.log" >&2
|
|
||||||
exit 1
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Regenerates every file under docs/output/. Each broker is started, measured and left running
|
|
||||||
# only for its own group of tests, because three brokers do not fit comfortably in memory on a
|
|
||||||
# small machine at the same time.
|
|
||||||
#
|
|
||||||
# Required environment:
|
|
||||||
# KAFKA_HOME unpacked kafka_2.13-4.2.1
|
|
||||||
# ERL_ROOT an Erlang 24 installation (RabbitMQ 3.10.x)
|
|
||||||
# RABBITMQ_HOME unpacked rabbitmq-server-generic-unix-3.10.25
|
|
||||||
# PULSAR_HOME unpacked apache-pulsar-4.2.4-bin
|
|
||||||
set -euo pipefail
|
|
||||||
cd "$(dirname "$0")/.."
|
|
||||||
mkdir -p docs/output
|
|
||||||
|
|
||||||
# Kafka needs no external broker for the measurements: spring-kafka-test starts a real KRaft
|
|
||||||
# broker in-process. KAFKA_HOME is only used by the footprint measurement.
|
|
||||||
mvn -B -Dgroups=kafka test 2>&1 | grep -E 'Running |Tests run:|BUILD ' > docs/output/tests.txt
|
|
||||||
|
|
||||||
scripts/rabbit-broker.sh
|
|
||||||
mvn -B -Dgroups=rabbit test 2>&1 | grep -E 'Running |Tests run:|BUILD ' >> docs/output/tests.txt
|
|
||||||
|
|
||||||
scripts/pulsar-broker.sh
|
|
||||||
mvn -B -Dgroups=pulsar test 2>&1 | grep -E 'Running |Tests run:|BUILD ' >> docs/output/tests.txt
|
|
||||||
|
|
||||||
{
|
|
||||||
echo "== Operational footprint, measured on one 2-core / 3.8 GB Linux box =="
|
|
||||||
echo
|
|
||||||
echo "Each broker started from its shipped distribution with default configuration and a"
|
|
||||||
echo "700 MB heap cap, on Temurin JDK 21. Times are one sample on a small box: treat them as"
|
|
||||||
echo "orders of magnitude, not as a benchmark."
|
|
||||||
echo
|
|
||||||
scripts/footprint.sh kafka; echo
|
|
||||||
scripts/footprint.sh rabbit; echo
|
|
||||||
scripts/footprint.sh pulsar
|
|
||||||
} > docs/output/footprint.txt
|
|
||||||
|
|
||||||
echo "regenerated:"; ls -1 docs/output
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package com.ankurm.brokers;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* There is deliberately no Spring application here. The measurements in src/test drive the three
|
|
||||||
* client libraries directly so that the thing being compared is the broker's delivery model and
|
|
||||||
* not three different sets of Spring defaults.
|
|
||||||
*
|
|
||||||
* <p>What each Spring Boot starter adds on top — and what it silently does not add, which
|
|
||||||
* in Boot 4 is more than people expect — is in docs/06-what-spring-adds.md.
|
|
||||||
*/
|
|
||||||
public final class BrokerComparisonApplication {
|
|
||||||
|
|
||||||
private BrokerComparisonApplication() {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
package com.ankurm.brokers;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
|
|
||||||
/** Writes a transcript under docs/output/. Nothing in the article is typed by hand. */
|
|
||||||
public final class Capture {
|
|
||||||
|
|
||||||
private Capture() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void write(String fileName, String heading, String body) {
|
|
||||||
Path dir = Path.of(System.getProperty("user.dir"), "docs", "output");
|
|
||||||
try {
|
|
||||||
Files.createDirectories(dir);
|
|
||||||
Files.writeString(dir.resolve(fileName), "== " + heading + " ==\n\n" + body + "\n");
|
|
||||||
}
|
|
||||||
catch (IOException ex) {
|
|
||||||
throw new IllegalStateException("could not write " + fileName, ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,232 +0,0 @@
|
|||||||
package com.ankurm.brokers;
|
|
||||||
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
|
||||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
|
||||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
|
||||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
|
||||||
import org.apache.kafka.clients.producer.KafkaProducer;
|
|
||||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
|
||||||
import org.apache.kafka.clients.producer.ProducerRecord;
|
|
||||||
import org.apache.kafka.common.TopicPartition;
|
|
||||||
import org.apache.kafka.common.serialization.StringDeserializer;
|
|
||||||
import org.apache.kafka.common.serialization.StringSerializer;
|
|
||||||
import org.junit.jupiter.api.AfterAll;
|
|
||||||
import org.junit.jupiter.api.BeforeAll;
|
|
||||||
import org.junit.jupiter.api.Tag;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Kafka measured against a real broker: an in-process KRaft broker from spring-kafka-test, one
|
|
||||||
* node, one topic, three partitions.
|
|
||||||
*
|
|
||||||
* <p>The three questions are the same for all three brokers: what ordering survives, what can be
|
|
||||||
* replayed, and how far consumers scale.
|
|
||||||
*/
|
|
||||||
@Tag("kafka")
|
|
||||||
class KafkaComparisonTest {
|
|
||||||
|
|
||||||
private static final String ORDERING = "orders-ordering";
|
|
||||||
|
|
||||||
private static final String REPLAY = "orders-replay";
|
|
||||||
|
|
||||||
private static final String SCALING = "orders-scaling";
|
|
||||||
|
|
||||||
private static EmbeddedKafkaKraftBroker broker;
|
|
||||||
|
|
||||||
@BeforeAll
|
|
||||||
static void startBroker() {
|
|
||||||
broker = new EmbeddedKafkaKraftBroker(1, 3, ORDERING, REPLAY, SCALING);
|
|
||||||
broker.afterPropertiesSet();
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterAll
|
|
||||||
static void stopBroker() {
|
|
||||||
broker.destroy();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- ordering
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void orderingIsPerPartitionOnly() {
|
|
||||||
produce(ORDERING, 12);
|
|
||||||
|
|
||||||
List<ConsumerRecord<String, String>> received = consumeAll(ORDERING, "ordering-group", 12);
|
|
||||||
|
|
||||||
Map<String, List<String>> perKey = new LinkedHashMap<>();
|
|
||||||
Map<String, Set<Integer>> partitionsPerKey = new LinkedHashMap<>();
|
|
||||||
List<String> globalOrder = new ArrayList<>();
|
|
||||||
for (ConsumerRecord<String, String> record : received) {
|
|
||||||
perKey.computeIfAbsent(record.key(), (k) -> new ArrayList<>()).add(record.value());
|
|
||||||
partitionsPerKey.computeIfAbsent(record.key(), (k) -> new java.util.TreeSet<>())
|
|
||||||
.add(record.partition());
|
|
||||||
globalOrder.add(record.key() + "=" + record.value() + "@p" + record.partition());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Per key, the sequence numbers must come back in the order they were produced. Compared
|
|
||||||
// as numbers: as strings, "10" sorts before "2" and the assertion is meaningless.
|
|
||||||
perKey.forEach((key, values) -> assertThat(values.stream().map(Integer::parseInt).toList())
|
|
||||||
.isSorted());
|
|
||||||
// Each key went to exactly one partition, which is why that holds...
|
|
||||||
partitionsPerKey.forEach((key, partitions) -> assertThat(partitions).hasSize(1));
|
|
||||||
// ...and the three keys are spread over all three partitions, so the transcript below is
|
|
||||||
// actually testing something.
|
|
||||||
assertThat(partitionsPerKey.values().stream().flatMap(Set::stream).distinct().count())
|
|
||||||
.isEqualTo(3);
|
|
||||||
List<Integer> asDelivered = globalOrder.stream()
|
|
||||||
.map((entry) -> Integer.parseInt(entry.split("=")[1].split("@")[0])).toList();
|
|
||||||
assertThat(asDelivered).isNotEqualTo(
|
|
||||||
java.util.stream.IntStream.rangeClosed(1, 12).boxed().toList());
|
|
||||||
|
|
||||||
StringBuilder body = new StringBuilder();
|
|
||||||
body.append("produced 12 records, keys D/A/F round-robin, values 1..12 in order\n")
|
|
||||||
.append("(keys chosen so that murmur2 spreads them: D->0, A->1, F->2. A, B and C\n")
|
|
||||||
.append(" all hash to partition 1 with three partitions, which is worth knowing\n")
|
|
||||||
.append(" before you decide your keys are well distributed.)\n\n");
|
|
||||||
body.append("consumed in this order:\n ").append(String.join("\n ", globalOrder))
|
|
||||||
.append("\n\nper key:\n");
|
|
||||||
perKey.forEach((key, values) -> body.append(" ").append(key).append(" -> partition ")
|
|
||||||
.append(partitionsPerKey.get(key)).append(" values ").append(values).append('\n'));
|
|
||||||
body.append("\nOrder is preserved within each key because a key hashes to one partition.\n")
|
|
||||||
.append("Across keys it is not: the values above are not 1..12 in order, because a\n")
|
|
||||||
.append("consumer drains one partition's buffer before the next.\n");
|
|
||||||
Capture.write("kafka-ordering.txt", "Kafka: ordering is per partition", body.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- replay
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void anythingStillWithinRetentionCanBeReadAgain() {
|
|
||||||
produce(REPLAY, 12);
|
|
||||||
|
|
||||||
int first = consumeAll(REPLAY, "replay-group-1", 12).size();
|
|
||||||
int again = consumeAll(REPLAY, "replay-group-2", 12).size();
|
|
||||||
|
|
||||||
List<ConsumerRecord<String, String>> third;
|
|
||||||
try (KafkaConsumer<String, String> consumer = consumer("replay-group-1")) {
|
|
||||||
consumer.subscribe(List.of(REPLAY));
|
|
||||||
consumer.poll(Duration.ofSeconds(2));
|
|
||||||
consumer.seekToBeginning(consumer.assignment());
|
|
||||||
third = drain(consumer, 12);
|
|
||||||
}
|
|
||||||
|
|
||||||
assertThat(first).isEqualTo(12);
|
|
||||||
assertThat(again).isEqualTo(12);
|
|
||||||
assertThat(third).hasSize(12);
|
|
||||||
|
|
||||||
Capture.write("kafka-replay.txt", "Kafka: the log is the storage",
|
|
||||||
"""
|
|
||||||
group replay-group-1, first read : %d records
|
|
||||||
group replay-group-2, brand new group : %d records
|
|
||||||
group replay-group-1, after seekToBeginning: %d records
|
|
||||||
|
|
||||||
Consuming does not remove anything. A consumer group is a cursor over a log
|
|
||||||
that the broker keeps until retention expires, so a new group, a reset
|
|
||||||
offset or a seek all read the same records again.
|
|
||||||
""".formatted(first, again, third.size()));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- consumer scaling
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void consumerParallelismIsCappedByPartitionCount() throws Exception {
|
|
||||||
produce(SCALING, 12);
|
|
||||||
|
|
||||||
List<KafkaConsumer<String, String>> consumers = new ArrayList<>();
|
|
||||||
Map<String, Set<Integer>> assignment = new LinkedHashMap<>();
|
|
||||||
try {
|
|
||||||
for (int i = 1; i <= 5; i++) {
|
|
||||||
KafkaConsumer<String, String> consumer = consumer("scaling-group");
|
|
||||||
consumer.subscribe(List.of(SCALING));
|
|
||||||
consumers.add(consumer);
|
|
||||||
}
|
|
||||||
// Poll each consumer until the group has settled and every member knows its share.
|
|
||||||
for (int round = 0; round < 8; round++) {
|
|
||||||
for (KafkaConsumer<String, String> consumer : consumers) {
|
|
||||||
consumer.poll(Duration.ofMillis(500));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (int i = 0; i < consumers.size(); i++) {
|
|
||||||
Set<Integer> partitions = new java.util.TreeSet<>();
|
|
||||||
for (TopicPartition tp : consumers.get(i).assignment()) {
|
|
||||||
partitions.add(tp.partition());
|
|
||||||
}
|
|
||||||
assignment.put("consumer-" + (i + 1), partitions);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
consumers.forEach(KafkaConsumer::close);
|
|
||||||
}
|
|
||||||
|
|
||||||
long idle = assignment.values().stream().filter(Set::isEmpty).count();
|
|
||||||
assertThat(assignment).hasSize(5);
|
|
||||||
assertThat(idle).isEqualTo(2);
|
|
||||||
|
|
||||||
StringBuilder body = new StringBuilder("topic 'orders-scaling', 3 partitions, 5 consumers in one group\n\n");
|
|
||||||
assignment.forEach((name, partitions) -> body.append(" ").append(name).append(" -> ")
|
|
||||||
.append(partitions.isEmpty() ? "no partitions (idle)" : "partitions " + partitions)
|
|
||||||
.append('\n'));
|
|
||||||
body.append("\nconsumers with no partitions: ").append(idle).append('\n')
|
|
||||||
.append("\nA partition is assigned to at most one consumer in a group, so the number\n")
|
|
||||||
.append("of partitions is a hard ceiling on consumer parallelism. Adding consumers\n")
|
|
||||||
.append("beyond it adds idle processes, not throughput.\n");
|
|
||||||
Capture.write("kafka-consumer-scaling.txt",
|
|
||||||
"Kafka: partitions are the ceiling on consumer parallelism", body.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- helpers
|
|
||||||
|
|
||||||
private void produce(String topic, int count) {
|
|
||||||
Properties props = new Properties();
|
|
||||||
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, broker.getBrokersAsString());
|
|
||||||
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
|
||||||
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
|
|
||||||
// D, A and F, not A, B and C: with three partitions murmur2 maps A, B and C all to
|
|
||||||
// partition 1, so the obvious choice of keys would have produced a transcript in which
|
|
||||||
// global order happened to be preserved and proved nothing. D->0, A->1, F->2.
|
|
||||||
String[] keys = { "D", "A", "F" };
|
|
||||||
try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
|
|
||||||
for (int i = 1; i <= count; i++) {
|
|
||||||
producer.send(new ProducerRecord<>(topic, keys[i % keys.length], String.valueOf(i)));
|
|
||||||
}
|
|
||||||
producer.flush();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private KafkaConsumer<String, String> consumer(String group) {
|
|
||||||
Properties props = new Properties();
|
|
||||||
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, broker.getBrokersAsString());
|
|
||||||
props.put(ConsumerConfig.GROUP_ID_CONFIG, group);
|
|
||||||
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
|
|
||||||
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
|
||||||
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
|
||||||
return new KafkaConsumer<>(props);
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<ConsumerRecord<String, String>> consumeAll(String topic, String group, int expected) {
|
|
||||||
try (KafkaConsumer<String, String> consumer = consumer(group)) {
|
|
||||||
consumer.subscribe(List.of(topic));
|
|
||||||
return drain(consumer, expected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<ConsumerRecord<String, String>> drain(KafkaConsumer<String, String> consumer, int expected) {
|
|
||||||
List<ConsumerRecord<String, String>> received = new ArrayList<>();
|
|
||||||
for (int i = 0; i < 20 && received.size() < expected; i++) {
|
|
||||||
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
|
|
||||||
records.forEach(received::add);
|
|
||||||
}
|
|
||||||
return received;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,298 +0,0 @@
|
|||||||
package com.ankurm.brokers;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import org.apache.pulsar.client.api.Consumer;
|
|
||||||
import org.apache.pulsar.client.api.Message;
|
|
||||||
import org.apache.pulsar.client.api.MessageId;
|
|
||||||
import org.apache.pulsar.client.api.Producer;
|
|
||||||
import org.apache.pulsar.client.api.PulsarClient;
|
|
||||||
import org.apache.pulsar.client.api.Schema;
|
|
||||||
import org.apache.pulsar.client.api.SubscriptionInitialPosition;
|
|
||||||
import org.apache.pulsar.client.api.SubscriptionType;
|
|
||||||
import org.junit.jupiter.api.AfterAll;
|
|
||||||
import org.junit.jupiter.api.BeforeAll;
|
|
||||||
import org.junit.jupiter.api.Tag;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pulsar measured against a real standalone broker on localhost:6650, started by
|
|
||||||
* scripts/pulsar-broker.sh.
|
|
||||||
*
|
|
||||||
* <p>Pulsar is the interesting third option because it does not force the trade the other two
|
|
||||||
* force. The subscription type is chosen per subscriber rather than being a property of the
|
|
||||||
* topic, so ordering and consumer fan-out are separate decisions.
|
|
||||||
*/
|
|
||||||
@Tag("pulsar")
|
|
||||||
class PulsarComparisonTest {
|
|
||||||
|
|
||||||
private static PulsarClient client;
|
|
||||||
|
|
||||||
@BeforeAll
|
|
||||||
static void connect() throws Exception {
|
|
||||||
client = PulsarClient.builder().serviceUrl("pulsar://127.0.0.1:6650").build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterAll
|
|
||||||
static void close() throws Exception {
|
|
||||||
client.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- ordering
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void sharedSpreadsAKeyAndKeySharedPinsIt() throws Exception {
|
|
||||||
String topic = "persistent://public/default/ordering-" + System.nanoTime();
|
|
||||||
produce(topic, 12);
|
|
||||||
|
|
||||||
Map<String, Set<String>> shared = consumersPerKey(topic, "sub-shared", SubscriptionType.Shared, 12);
|
|
||||||
Map<String, Set<String>> keyShared = consumersPerKey(topic, "sub-keyshared",
|
|
||||||
SubscriptionType.Key_Shared, 12);
|
|
||||||
|
|
||||||
// Key_Shared: every key was handled by exactly one consumer, so per-key order is safe.
|
|
||||||
keyShared.forEach((key, handlers) -> assertThat(handlers).hasSize(1));
|
|
||||||
// Shared: at least one key was handled by both, so two messages with that key were in
|
|
||||||
// flight on two consumers and nothing orders them.
|
|
||||||
assertThat(shared.values().stream().anyMatch((handlers) -> handlers.size() > 1)).isTrue();
|
|
||||||
|
|
||||||
Capture.write("pulsar-ordering.txt", "Pulsar: the subscription type decides",
|
|
||||||
"""
|
|
||||||
12 messages, keys A/B/C, values 1..12 in order, two consumers per
|
|
||||||
subscription, receiverQueueSize 1 so the first consumer cannot take the
|
|
||||||
whole backlog.
|
|
||||||
|
|
||||||
Shared subscription, which consumers saw each key:
|
|
||||||
%s
|
|
||||||
Key_Shared subscription, which consumers saw each key:
|
|
||||||
%s
|
|
||||||
A Shared subscription round-robins individual messages, so messages with
|
|
||||||
the same key end up on different consumers and can be processed at the
|
|
||||||
same time: there is no per-key order left to speak of. Key_Shared hashes
|
|
||||||
the key to one consumer, which is Kafka's guarantee -- except that the
|
|
||||||
assignment belongs to the subscription and is recomputed as consumers come
|
|
||||||
and go, rather than being fixed by a partition count chosen when the topic
|
|
||||||
was created.
|
|
||||||
""".formatted(render3(shared), render3(keyShared)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- replay
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void aSubscriptionCanBeRewound() throws Exception {
|
|
||||||
String topic = "persistent://public/default/replay-" + System.nanoTime();
|
|
||||||
produce(topic, 12);
|
|
||||||
|
|
||||||
int first;
|
|
||||||
int afterSeek;
|
|
||||||
try (Consumer<String> consumer = consumer(topic, "replay-sub", SubscriptionType.Exclusive)) {
|
|
||||||
first = drain(consumer, 12).size();
|
|
||||||
consumer.seek(MessageId.earliest);
|
|
||||||
afterSeek = drain(consumer, 12).size();
|
|
||||||
}
|
|
||||||
|
|
||||||
int newSubscription;
|
|
||||||
try (Consumer<String> consumer = consumer(topic, "replay-sub-2", SubscriptionType.Exclusive)) {
|
|
||||||
newSubscription = drain(consumer, 12).size();
|
|
||||||
}
|
|
||||||
|
|
||||||
assertThat(first).isEqualTo(12);
|
|
||||||
assertThat(afterSeek).isEqualTo(12);
|
|
||||||
assertThat(newSubscription).isEqualTo(12);
|
|
||||||
|
|
||||||
Capture.write("pulsar-replay.txt", "Pulsar: acknowledged, but still there",
|
|
||||||
"""
|
|
||||||
subscription replay-sub, first read : %d messages
|
|
||||||
subscription replay-sub, after seek(earliest): %d messages
|
|
||||||
subscription replay-sub-2, brand new : %d messages
|
|
||||||
|
|
||||||
Acknowledgement moves a cursor; the message itself lives in the managed
|
|
||||||
ledger. seek(MessageId) and seek(timestamp) rewind a live subscription,
|
|
||||||
which Kafka can also do by resetting offsets. What differs is the default:
|
|
||||||
Pulsar deletes a message once every subscription has acknowledged it,
|
|
||||||
unless a retention policy on the namespace says otherwise, whereas Kafka
|
|
||||||
keeps it for the retention period regardless of who read it. A Pulsar
|
|
||||||
topic with no retention policy and no subscriptions keeps nothing.
|
|
||||||
""".formatted(first, afterSeek, newSubscription));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- consumer scaling
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void sharedSubscriptionsHaveNoPartitionCeilingButHaveAReceiverQueue() throws Exception {
|
|
||||||
String topicA = "persistent://public/default/scaling-default-" + System.nanoTime();
|
|
||||||
produce(topicA, 40);
|
|
||||||
Map<String, Integer> withDefaultQueue = drainAcross(topicA, "scaling-sub", 5, 40, 0);
|
|
||||||
|
|
||||||
String topicB = "persistent://public/default/scaling-q1-" + System.nanoTime();
|
|
||||||
produce(topicB, 40);
|
|
||||||
Map<String, Integer> withQueueOfOne = drainAcross(topicB, "scaling-sub", 5, 40, 1);
|
|
||||||
|
|
||||||
long idleDefault = withDefaultQueue.values().stream().filter((n) -> n == 0).count();
|
|
||||||
long idleTuned = withQueueOfOne.values().stream().filter((n) -> n == 0).count();
|
|
||||||
|
|
||||||
assertThat(idleTuned).isZero();
|
|
||||||
assertThat(idleDefault).isGreaterThan(0);
|
|
||||||
|
|
||||||
Capture.write("pulsar-consumer-scaling.txt",
|
|
||||||
"Pulsar: no partition ceiling, but the receiver queue decides who gets the work",
|
|
||||||
"""
|
|
||||||
one non-partitioned topic, 40 messages, 5 consumers, Shared subscription
|
|
||||||
|
|
||||||
receiverQueueSize left at the default (1000):
|
|
||||||
%s consumers that received nothing : %d
|
|
||||||
|
|
||||||
receiverQueueSize(1):
|
|
||||||
%s consumers that received nothing : %d
|
|
||||||
|
|
||||||
The topic has no partitions and five consumers can still share the work --
|
|
||||||
in Kafka the same shape needs at least five partitions, chosen when the
|
|
||||||
topic was created. But the default receiver queue is 1000 messages, so the
|
|
||||||
first consumers to connect pull the whole 40-message backlog into their own
|
|
||||||
buffers before the rest ask for anything, and the subscription looks
|
|
||||||
broken. Which consumers win is a race and varies between runs -- one
|
|
||||||
consumer taking all forty, or two taking twenty each -- but the consumers
|
|
||||||
that lose it see nothing at all. This is the same trap as RabbitMQ's
|
|
||||||
unbounded prefetch, with a different name and a much larger default.
|
|
||||||
""".formatted(render2(withDefaultQueue), idleDefault,
|
|
||||||
render2(withQueueOfOne), idleTuned));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- helpers
|
|
||||||
|
|
||||||
private void produce(String topic, int count) throws Exception {
|
|
||||||
String[] keys = { "A", "B", "C" };
|
|
||||||
try (Producer<String> producer = client.newProducer(Schema.STRING).topic(topic).create()) {
|
|
||||||
for (int i = 1; i <= count; i++) {
|
|
||||||
producer.newMessage().key(keys[i % keys.length]).value(String.valueOf(i)).send();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Consumer<String> consumer(String topic, String subscription, SubscriptionType type)
|
|
||||||
throws Exception {
|
|
||||||
return consumer(topic, subscription, type, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param receiverQueueSize 0 leaves Pulsar's default of 1000 in place; anything else sets it.
|
|
||||||
* The default matters more than it looks: it is how many messages a single consumer will pull
|
|
||||||
* into its own buffer before another consumer on the same subscription gets a chance.
|
|
||||||
*/
|
|
||||||
private Consumer<String> consumer(String topic, String subscription, SubscriptionType type,
|
|
||||||
int receiverQueueSize) throws Exception {
|
|
||||||
var builder = client.newConsumer(Schema.STRING)
|
|
||||||
.topic(topic)
|
|
||||||
.subscriptionName(subscription)
|
|
||||||
.subscriptionType(type)
|
|
||||||
.subscriptionInitialPosition(SubscriptionInitialPosition.Earliest);
|
|
||||||
if (receiverQueueSize > 0) {
|
|
||||||
builder = builder.receiverQueueSize(receiverQueueSize);
|
|
||||||
}
|
|
||||||
return builder.subscribe();
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> drain(Consumer<String> consumer, int expected) throws Exception {
|
|
||||||
List<String> received = new ArrayList<>();
|
|
||||||
while (received.size() < expected) {
|
|
||||||
Message<String> message = consumer.receive(2, TimeUnit.SECONDS);
|
|
||||||
if (message == null) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
received.add(message.getValue());
|
|
||||||
consumer.acknowledge(message);
|
|
||||||
}
|
|
||||||
return received;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Which consumers saw each key, with a receiver queue of one so nothing hoards. */
|
|
||||||
private Map<String, Set<String>> consumersPerKey(String topic, String subscription,
|
|
||||||
SubscriptionType type, int expected) throws Exception {
|
|
||||||
Map<String, Set<String>> perKey = new LinkedHashMap<>();
|
|
||||||
List<Consumer<String>> consumers = new ArrayList<>();
|
|
||||||
try {
|
|
||||||
consumers.add(consumer(topic, subscription, type, 1));
|
|
||||||
consumers.add(consumer(topic, subscription, type, 1));
|
|
||||||
int received = 0;
|
|
||||||
while (received < expected) {
|
|
||||||
boolean any = false;
|
|
||||||
for (int i = 0; i < consumers.size(); i++) {
|
|
||||||
Message<String> message = consumers.get(i).receive(500, TimeUnit.MILLISECONDS);
|
|
||||||
if (message != null) {
|
|
||||||
perKey.computeIfAbsent(message.getKey(), (k) -> new java.util.TreeSet<>())
|
|
||||||
.add("consumer-" + (i + 1));
|
|
||||||
consumers.get(i).acknowledge(message);
|
|
||||||
received++;
|
|
||||||
any = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!any) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
for (Consumer<String> consumer : consumers) {
|
|
||||||
consumer.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return perKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drains a Shared subscription across {@code n} consumers and reports the distribution. */
|
|
||||||
private Map<String, Integer> drainAcross(String topic, String subscription, int n, int expected,
|
|
||||||
int receiverQueueSize) throws Exception {
|
|
||||||
Map<String, Integer> counts = new LinkedHashMap<>();
|
|
||||||
List<Consumer<String>> consumers = new ArrayList<>();
|
|
||||||
try {
|
|
||||||
for (int i = 1; i <= n; i++) {
|
|
||||||
consumers.add(consumer(topic, subscription, SubscriptionType.Shared, receiverQueueSize));
|
|
||||||
counts.put("consumer-" + i, 0);
|
|
||||||
}
|
|
||||||
int received = 0;
|
|
||||||
while (received < expected) {
|
|
||||||
boolean any = false;
|
|
||||||
for (int i = 0; i < consumers.size(); i++) {
|
|
||||||
Message<String> message = consumers.get(i).receive(300, TimeUnit.MILLISECONDS);
|
|
||||||
if (message != null) {
|
|
||||||
consumers.get(i).acknowledge(message);
|
|
||||||
counts.merge("consumer-" + (i + 1), 1, Integer::sum);
|
|
||||||
received++;
|
|
||||||
any = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!any) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
for (Consumer<String> consumer : consumers) {
|
|
||||||
consumer.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return counts;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String render3(Map<String, Set<String>> perKey) {
|
|
||||||
StringBuilder out = new StringBuilder();
|
|
||||||
perKey.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach((entry) ->
|
|
||||||
out.append(" ").append(entry.getKey()).append(" -> ").append(entry.getValue())
|
|
||||||
.append('\n'));
|
|
||||||
return out.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String render2(Map<String, Integer> counts) {
|
|
||||||
StringBuilder out = new StringBuilder();
|
|
||||||
counts.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach((entry) ->
|
|
||||||
out.append(" ").append(entry.getKey()).append(" -> ").append(entry.getValue())
|
|
||||||
.append(" messages\n"));
|
|
||||||
return out.toString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,286 +0,0 @@
|
|||||||
package com.ankurm.brokers;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
|
||||||
import java.util.concurrent.CountDownLatch;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
|
||||||
|
|
||||||
import com.rabbitmq.client.AMQP;
|
|
||||||
import com.rabbitmq.client.Channel;
|
|
||||||
import com.rabbitmq.client.Connection;
|
|
||||||
import com.rabbitmq.client.ConnectionFactory;
|
|
||||||
import com.rabbitmq.client.DefaultConsumer;
|
|
||||||
import com.rabbitmq.client.Envelope;
|
|
||||||
import com.rabbitmq.client.GetResponse;
|
|
||||||
import org.junit.jupiter.api.AfterAll;
|
|
||||||
import org.junit.jupiter.api.BeforeAll;
|
|
||||||
import org.junit.jupiter.api.Tag;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* RabbitMQ measured against a real broker on localhost:5672, started by
|
|
||||||
* scripts/rabbit-broker.sh.
|
|
||||||
*
|
|
||||||
* <p>The same three questions as the Kafka measurements, against a broker that owns the message
|
|
||||||
* until it is acknowledged rather than a log that keeps it.
|
|
||||||
*/
|
|
||||||
@Tag("rabbit")
|
|
||||||
class RabbitComparisonTest {
|
|
||||||
|
|
||||||
private static Connection connection;
|
|
||||||
|
|
||||||
@BeforeAll
|
|
||||||
static void connect() throws Exception {
|
|
||||||
ConnectionFactory factory = new ConnectionFactory();
|
|
||||||
factory.setHost("127.0.0.1");
|
|
||||||
factory.setPort(5672);
|
|
||||||
connection = factory.newConnection();
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterAll
|
|
||||||
static void close() throws Exception {
|
|
||||||
connection.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- ordering
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void oneConsumerIsFifoAndTwoConsumersAreNot() throws Exception {
|
|
||||||
String single = declare("order-single");
|
|
||||||
publish(single, 12);
|
|
||||||
List<String> fifo = getAll(single, 12);
|
|
||||||
|
|
||||||
String shared = declare("order-shared");
|
|
||||||
publish(shared, 12);
|
|
||||||
List<String> completionOrder = consumeWithTwoConsumers(shared, 12);
|
|
||||||
|
|
||||||
assertThat(fifo).containsExactly("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12");
|
|
||||||
|
|
||||||
int inversions = 0;
|
|
||||||
for (int i = 1; i < completionOrder.size(); i++) {
|
|
||||||
if (Integer.parseInt(completionOrder.get(i)) < Integer.parseInt(completionOrder.get(i - 1))) {
|
|
||||||
inversions++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Capture.write("rabbit-ordering.txt", "RabbitMQ: FIFO per queue, per consumer",
|
|
||||||
"""
|
|
||||||
one queue, one consumer, 12 messages
|
|
||||||
completion order : %s
|
|
||||||
|
|
||||||
one queue, two consumers, prefetch 1, consumer-1 slower than consumer-2
|
|
||||||
completion order : %s
|
|
||||||
out-of-order steps: %d
|
|
||||||
|
|
||||||
A queue is FIFO and a single consumer sees it that way. The moment a second
|
|
||||||
consumer is added the broker hands the next message to whichever consumer
|
|
||||||
is free, so the order in which work finishes is no longer the order in
|
|
||||||
which it was published. There is no key: RabbitMQ has no notion of a
|
|
||||||
partition to which related messages could be pinned. Ordering across
|
|
||||||
related messages means one queue and one consumer, and therefore no
|
|
||||||
horizontal scaling for that queue -- or a consistent-hash exchange, which
|
|
||||||
is a plugin.
|
|
||||||
""".formatted(fifo, completionOrder, inversions));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- replay
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void anAcknowledgedMessageIsGone() throws Exception {
|
|
||||||
String queue = declare("replay-probe");
|
|
||||||
publish(queue, 12);
|
|
||||||
|
|
||||||
List<String> first = getAll(queue, 12);
|
|
||||||
List<String> second = getAll(queue, 12);
|
|
||||||
|
|
||||||
int depth = depth(queue);
|
|
||||||
|
|
||||||
assertThat(first).hasSize(12);
|
|
||||||
assertThat(second).isEmpty();
|
|
||||||
assertThat(depth).isZero();
|
|
||||||
|
|
||||||
Capture.write("rabbit-replay.txt", "RabbitMQ: there is nothing to replay",
|
|
||||||
"""
|
|
||||||
first drain of the queue : %d messages
|
|
||||||
second drain of the queue : %d messages
|
|
||||||
queue depth afterwards : %d
|
|
||||||
|
|
||||||
Acknowledging a message deletes it. The broker is a router with buffers,
|
|
||||||
not a log: there is no offset to rewind and no second reader that can see
|
|
||||||
what the first one consumed. Reading the same message twice means
|
|
||||||
arranging it in advance -- a second queue bound to the same exchange, or a
|
|
||||||
copy written somewhere else -- and it cannot be arranged after the fact.
|
|
||||||
""".formatted(first.size(), second.size(), depth));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- consumer scaling
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void consumersScaleWithoutAPartitionCeilingButPrefetchDecidesWho() throws Exception {
|
|
||||||
String unlimited = declare("scaling-unlimited");
|
|
||||||
publish(unlimited, 40);
|
|
||||||
Map<String, Integer> withDefaultPrefetch = drainAcross(unlimited, 5, 40, 0);
|
|
||||||
|
|
||||||
String throttled = declare("scaling-prefetch-1");
|
|
||||||
publish(throttled, 40);
|
|
||||||
Map<String, Integer> withPrefetchOne = drainAcross(throttled, 5, 40, 1);
|
|
||||||
|
|
||||||
long idleDefault = withDefaultPrefetch.values().stream().filter((n) -> n == 0).count();
|
|
||||||
long idleTuned = withPrefetchOne.values().stream().filter((n) -> n == 0).count();
|
|
||||||
|
|
||||||
assertThat(idleTuned).isZero();
|
|
||||||
|
|
||||||
Capture.write("rabbit-consumer-scaling.txt",
|
|
||||||
"RabbitMQ: consumers scale, and prefetch decides whether they actually do",
|
|
||||||
"""
|
|
||||||
one queue, 40 messages, 5 consumers, each taking 10 ms per message
|
|
||||||
|
|
||||||
no basicQos at all (unlimited prefetch, the AMQP default):
|
|
||||||
%s consumers that received nothing : %d
|
|
||||||
|
|
||||||
basicQos(1):
|
|
||||||
%s consumers that received nothing : %d
|
|
||||||
|
|
||||||
Every consumer on a queue competes for the same messages, so adding
|
|
||||||
consumers adds throughput and there is no structural ceiling of the kind
|
|
||||||
Kafka's partition count imposes. But with the AMQP default the broker
|
|
||||||
pushes as many messages as a consumer will take, so whichever consumer
|
|
||||||
connects first can be handed the entire backlog while the others sit idle.
|
|
||||||
basicQos is not a tuning knob you get to postpone; it is what makes the
|
|
||||||
fan-out real. Spring AMQP sets it for you --
|
|
||||||
AbstractMessageListenerContainer.DEFAULT_PREFETCH_COUNT is 250 -- which is
|
|
||||||
better than unlimited and still large enough to concentrate a small
|
|
||||||
backlog on one consumer.
|
|
||||||
|
|
||||||
The price of all this is the ordering measurement: there is no key, so
|
|
||||||
nothing constrains related messages to one consumer.
|
|
||||||
""".formatted(render(withDefaultPrefetch), idleDefault,
|
|
||||||
render(withPrefetchOne), idleTuned));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- helpers
|
|
||||||
|
|
||||||
private String declare(String name) throws Exception {
|
|
||||||
try (Channel channel = connection.createChannel()) {
|
|
||||||
channel.queueDelete(name);
|
|
||||||
channel.queueDeclare(name, false, false, true, null);
|
|
||||||
}
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void publish(String queue, int count) throws Exception {
|
|
||||||
try (Channel channel = connection.createChannel()) {
|
|
||||||
for (int i = 1; i <= count; i++) {
|
|
||||||
channel.basicPublish("", queue, null, String.valueOf(i).getBytes(StandardCharsets.UTF_8));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> getAll(String queue, int max) throws Exception {
|
|
||||||
List<String> received = new ArrayList<>();
|
|
||||||
try (Channel channel = connection.createChannel()) {
|
|
||||||
for (int i = 0; i < max; i++) {
|
|
||||||
GetResponse response = channel.basicGet(queue, true);
|
|
||||||
if (response == null) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
received.add(new String(response.getBody(), StandardCharsets.UTF_8));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return received;
|
|
||||||
}
|
|
||||||
|
|
||||||
private int depth(String queue) throws Exception {
|
|
||||||
try (Channel channel = connection.createChannel()) {
|
|
||||||
return channel.queueDeclarePassive(queue).getMessageCount();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> consumeWithTwoConsumers(String queue, int count) throws Exception {
|
|
||||||
List<String> completion = new CopyOnWriteArrayList<>();
|
|
||||||
CountDownLatch done = new CountDownLatch(count);
|
|
||||||
List<Channel> channels = new ArrayList<>();
|
|
||||||
for (int i = 1; i <= 2; i++) {
|
|
||||||
long delay = (i == 1) ? 60 : 5;
|
|
||||||
Channel channel = connection.createChannel();
|
|
||||||
channel.basicQos(1);
|
|
||||||
channels.add(channel);
|
|
||||||
channel.basicConsume(queue, false, new DefaultConsumer(channel) {
|
|
||||||
@Override
|
|
||||||
public void handleDelivery(String tag, Envelope envelope, AMQP.BasicProperties props,
|
|
||||||
byte[] body) throws IOException {
|
|
||||||
try {
|
|
||||||
Thread.sleep(delay);
|
|
||||||
}
|
|
||||||
catch (InterruptedException ex) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
}
|
|
||||||
completion.add(new String(body, StandardCharsets.UTF_8));
|
|
||||||
getChannel().basicAck(envelope.getDeliveryTag(), false);
|
|
||||||
done.countDown();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
done.await(30, TimeUnit.SECONDS);
|
|
||||||
for (Channel channel : channels) {
|
|
||||||
channel.close();
|
|
||||||
}
|
|
||||||
return List.copyOf(completion);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drains a queue across {@code n} competing consumers. prefetch 0 means "do not set it". */
|
|
||||||
private Map<String, Integer> drainAcross(String queue, int n, int expected, int prefetch)
|
|
||||||
throws Exception {
|
|
||||||
Map<String, AtomicInteger> perConsumer = new ConcurrentHashMap<>();
|
|
||||||
CountDownLatch done = new CountDownLatch(expected);
|
|
||||||
List<Channel> channels = new ArrayList<>();
|
|
||||||
for (int i = 1; i <= n; i++) {
|
|
||||||
String name = "consumer-" + i;
|
|
||||||
Channel channel = connection.createChannel();
|
|
||||||
if (prefetch > 0) {
|
|
||||||
channel.basicQos(prefetch);
|
|
||||||
}
|
|
||||||
channels.add(channel);
|
|
||||||
perConsumer.put(name, new AtomicInteger());
|
|
||||||
channel.basicConsume(queue, false, new DefaultConsumer(channel) {
|
|
||||||
@Override
|
|
||||||
public void handleDelivery(String tag, Envelope envelope, AMQP.BasicProperties props,
|
|
||||||
byte[] body) throws IOException {
|
|
||||||
perConsumer.get(name).incrementAndGet();
|
|
||||||
try {
|
|
||||||
Thread.sleep(10);
|
|
||||||
}
|
|
||||||
catch (InterruptedException ex) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
}
|
|
||||||
getChannel().basicAck(envelope.getDeliveryTag(), false);
|
|
||||||
done.countDown();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
done.await(30, TimeUnit.SECONDS);
|
|
||||||
for (Channel channel : channels) {
|
|
||||||
channel.close();
|
|
||||||
}
|
|
||||||
Map<String, Integer> counts = new LinkedHashMap<>();
|
|
||||||
perConsumer.forEach((name, count) -> counts.put(name, count.get()));
|
|
||||||
return counts;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String render(Map<String, Integer> counts) {
|
|
||||||
StringBuilder out = new StringBuilder();
|
|
||||||
counts.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach((entry) ->
|
|
||||||
out.append(" ").append(entry.getKey()).append(" -> ").append(entry.getValue())
|
|
||||||
.append(" messages\n"));
|
|
||||||
return out.toString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
target/
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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;
|
|
||||||
@@ -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
|
|
||||||
@@ -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>
|
|
||||||
@@ -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/^ +//'
|
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -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) --> orders --> priceOrder (Function) --> invoices --> 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");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user