Add amqp10 module: AMQP 1.0 in Spring Boot 4.2 with RabbitMQ 4

Generic spring-boot-starter-amqp (AmqpClient, @AmqpListener) and RabbitMQ's own AMQP 1.0 client
against a real RabbitMQ 4.4.1 broker via Testcontainers. Transcripts in amqp10/output/ are written
by the tests; no docs/ folder.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b44H98Yd627wauSpzA
This commit is contained in:
Ankur Mhatre
2026-11-25 23:27:57 +05:30
co-authored by Claude Sonnet 5.5
parent 78fc41e586
commit e54cf840fd
34 changed files with 1320 additions and 0 deletions
+1
View File
@@ -17,6 +17,7 @@ directly under `output/` instead, with the equivalent depth in the article's own
| [`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 &mdash; choreography and orchestration &mdash; 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 | | [`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 &mdash; choreography and orchestration &mdash; 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 | | [`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 | | [`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 |
The brokers make an instructive set. Kafka's consumer holds an offset and the broker remembers The brokers make an instructive set. Kafka's consumer holds an offset and the broker remembers
nothing about individual records; RabbitMQ's broker owns the message until it is acknowledged and nothing about individual records; RabbitMQ's broker owns the message until it is acknowledged and
+47
View File
@@ -0,0 +1,47 @@
# amqp10 — AMQP 1.0 in Spring Boot 4.2 with RabbitMQ 4
Companion code for the ankurm.com article *AMQP 1.0 in Spring Boot 4.2 with RabbitMQ 4*. Every
number in the article comes from a file in [`output/`](output), written by the test suite against a
real RabbitMQ broker started by Testcontainers.
| Piece | Version | Where it was read from |
|---|---|---|
| Spring Boot | 4.2.0 (GA 19 Nov 2026) | `maven-metadata.xml` |
| Spring Framework / Spring AMQP | 7.1.0 / 4.2.0 | Boot's dependency management |
| protonj2-client (generic AMQP 1.0) | 1.4.0 | `spring-boot-amqp` 4.2.0 pom |
| RabbitMQ AMQP 1.0 client | `com.rabbitmq.client:amqp-client` 1.7.0, via `spring-boot-starter-amqp-rabbitmq` 4.2.0 | resolved dependency tree |
| Broker | RabbitMQ 4.4.1 on Erlang 29.1.3 | `rabbitmq:4-management`, see `output/01-broker.txt` |
| JDK | Temurin 25.0.5.1 | |
| Testcontainers | 2.0.5 (`testcontainers-rabbitmq`) | Boot's BOM |
Boot 4.2 has three AMQP starters: `spring-boot-starter-amqp` (generic AMQP 1.0), `spring-boot-starter-amqp-rabbitmq`
(RabbitMQ's own AMQP 1.0 client) and `spring-boot-starter-rabbitmq` (classic AMQP 0-9-1). This module uses the first
two and talks to the third with a plain `RabbitTemplate` in the interop test.
## Run it
```bash
export JAVA_HOME=/path/to/jdk-25
./scripts/run-all.sh # needs Docker: Testcontainers starts rabbitmq:4-management
```
## What the tests show
| Test | Transcript | What it demonstrates |
|---|---|---|
| `Test01BrokerTest` | `01-broker.txt` | Broker version, enabled plugins: AMQP 1.0 needs no plugin on 4.x |
| `Test02GenericTest` | `02-generic-send-receive.txt`, `03-generic-pull-and-peek.txt` | `spring-boot-starter-amqp`: `AmqpClient` + `@AmqpListener`, how a message looks to the broker, and the untyped-pull trap that loses a message |
| `Test04AddressFailuresTest` | `04-address-failures.txt` | Which address forms work and what RELEASED / REJECTED mean |
| `Test05CredentialsTest` | `05-connection-mistakes.txt` | No credentials, wrong password, wrong port |
| `Test06RabbitClientTest` | `06-rabbit-client.txt` | `spring-boot-starter-amqp-rabbitmq`: auto-configured beans, declared topology, publish with confirms, `@RabbitListener` |
| `Test07InteropTest` | `07-classic-interop.txt` | One queue written by AMQP 0-9-1 and read by AMQP 1.0, and back |
| `Test08PoisonTest` | `08-poison-default.txt` | A throwing `@AmqpListener` kills its consumer under Boot's defaults |
| `Test09HandledTest` | `09-poison-with-error-handler.txt` | The same listeners with a container `ErrorHandler` |
| `scripts/compare-starters.sh` | `10-starter-comparison.txt` | What the two Boot starters contain, read from their jars |
Main sources: [`GenericOrderListener`](src/main/java/com/ankurm/amqp10/GenericOrderListener.java),
[`RabbitSpecificConfig`](src/main/java/com/ankurm/amqp10/RabbitSpecificConfig.java),
[`PoisonListeners`](src/main/java/com/ankurm/amqp10/PoisonListeners.java),
[`HandledFactoryConfig`](src/main/java/com/ankurm/amqp10/HandledFactoryConfig.java).
There is no `docs/` folder: the explanations live in the article's own collapsible sections.
+12
View File
@@ -0,0 +1,12 @@
$ 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
@@ -0,0 +1,9 @@
$ 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
@@ -0,0 +1,11 @@
what the broker holds (management API, 0-9-1 view of an AMQP 1.0 message):
payload = {"id":"p-1","item":"mouse","qty":3}
content_type = application/json
headers = {"__TypeId__":"com.ankurm.amqp10.OrderMessage"}
depth before pulling = 2
$ untyped: Object o = from("/queues/orders.pull").receiveAndConvert().get()
-> java.lang.IllegalArgumentException: The class 'com.ankurm.amqp10.OrderMessage' is not in the trusted packages: [java.util, jav...
depth after the failed conversion = 1
$ typed: CompletableFuture<OrderMessage> f = from(...).receiveAndConvert()
-> OrderMessage[id=p-2, item=dock, qty=1]
depth after the typed pull = 0
+10
View File
@@ -0,0 +1,10 @@
to("/queues/orders.generic")
returned true after 13 ms
to("/queues/does.not.exist")
threw AmqpClientNackReceivedException: The message was not accepted, but RELEASED after 5 ms
to("orders.generic")
threw AmqpClientNackReceivedException: The message was not accepted, but REJECTED after 5 ms
to("/queue/orders.generic")
threw AmqpClientNackReceivedException: The message was not accepted, but REJECTED after 2 ms
to("/exchanges/amq.direct/nobody-listens")
threw AmqpClientNackReceivedException: The message was not accepted, but RELEASED after 2 ms
+12
View File
@@ -0,0 +1,12 @@
no spring.amqp.username / password set:
context started = true
send -> true (context up in 953 ms); broker sees: {1, 0} guest
username=guest password=wrong:
context started = false
javax.security.sasl.AuthenticationException: SASL exchange failed to authenticate client (3271 ms)
username=guest password=guest:
context started = true
send -> true (context up in 988 ms); broker sees: {1, 0} guest
port=1 (nothing listens):
context started = false
java.net.ConnectException: finishConnect(..) failed with error(-111): Connection refused (202 ms)
+14
View File
@@ -0,0 +1,14 @@
beans from spring-boot-starter-amqp-rabbitmq (no @Bean written for them):
RabbitAmqpTemplate [rabbitAmqpTemplate]
RabbitAmqpAdmin [rabbitAmqpAdmin]
RabbitAmqpListenerContainerFactory [rabbitListenerContainerFactory]
AmqpConnectionFactory [amqpRabbitConnectionFactory]
declared by RabbitAmqpAdmin:
queue orders.rabbit type=quorum durable=true
exchange orders.topic type=topic
binding orders.topic -> orders.rabbit key=orders.created
$ template.convertAndSend("orders.topic", "orders.created", order).get() -> true
@RabbitListener(queues = "orders.rabbit") received OrderMessage[id=r-1, item=router, qty=2]
unroutable key : threw AmqpNackReceivedException: The message was rejected after 4 ms
missing exchange: threw AmqpMessageRejectedException: no exchange 'no.such.exchange' in vhost '/' after 2 ms
$ rabbitmqctl list_connections protocol -> an AMQP 1.0 connection is open: true
+16
View File
@@ -0,0 +1,16 @@
0-9-1 producer (RabbitTemplate) -> AMQP 1.0 consumer (AmqpClient.receive):
body = {"id":"i-1","item":"classic","qty":1}
messageId = m-classic
correlationId = c-classic
contentType = application/json
deliveryMode = null
headers = {attempt=3, tenant=acme}
AMQP 1.0 producer (AmqpClient.to) -> 0-9-1 consumer (RabbitTemplate.receive):
body = {"id":"i-2","item":"amqp10","qty":2}
messageId = m-amqp10
correlationId = c-amqp10
contentType = application/json
deliveryMode = PERSISTENT
headers = {__TypeId__=com.ankurm.amqp10.OrderMessage, attempt=3, tenant=acme}
$ rabbitmqctl list_connections protocol, while both clients are connected:
AMQP 0-9-1 connection open = true, AMQP 1.0 connection open = true
+7
View File
@@ -0,0 +1,7 @@
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
@@ -0,0 +1,6 @@
container errorHandler = set (lambda)
with a container ErrorHandler (HandledFactoryConfig), one bad message per queue:
plain exception, autoAccept default : 1 attempt(s); follow-up good-1 reached the listener = true
AmqpRejectAndDontRequeueException : 1 attempt(s)
plain exception, autoAccept=false : 1877 attempts in 3 seconds (figure varies per run, still counting)
queue orders.poison.manual depth now : 2
+57
View File
@@ -0,0 +1,57 @@
Spring Boot 4.2.0
== spring-boot-starter-amqp: description and dependencies
<description>Starter for generic AMQP 1.0 support</description>
<artifactId>spring-boot-amqp</artifactId>
== spring-boot-starter-amqp-rabbitmq: description and dependencies
<description>Starter for using Spring AMQP with Rabbit MQ over AMQP 1.0 protocol</description>
<artifactId>spring-boot-amqp-rabbitmq</artifactId>
== spring-boot-starter-rabbitmq: description and dependencies
<description>Starter for using RabbitMQ messaging and streaming broker</description>
<artifactId>spring-boot-rabbitmq</artifactId>
== spring-boot-amqp auto-configuration classes
org.springframework.boot.amqp.autoconfigure.AmqpAutoConfiguration
== spring-boot-amqp properties (spring.amqp.*)
spring.amqp.client.completion-timeout default=60s
spring.amqp.client.default-to-address default=None
spring.amqp.host default=localhost
spring.amqp.listener.auto-startup default=True
spring.amqp.listener.concurrency default=1
spring.amqp.listener.default-requeue-rejected default=True
spring.amqp.listener.graceful-shutdown-period default=30s
spring.amqp.listener.initial-credits default=100
spring.amqp.listener.receive-timeout default=1s
spring.amqp.password default=None
spring.amqp.port default=5672
spring.amqp.username default=None
== spring-boot-amqp-rabbitmq auto-configuration classes
org.springframework.boot.amqp.rabbitmq.autoconfigure.AmqpRabbitAutoConfiguration
org.springframework.boot.amqp.rabbitmq.autoconfigure.health.AmqpRabbitHealthContributorAutoConfiguration
== spring-boot-amqp-rabbitmq properties (spring.amqp.rabbitmq.*)
spring.amqp.rabbitmq.address default=None
spring.amqp.rabbitmq.host default=localhost
spring.amqp.rabbitmq.password default=None
spring.amqp.rabbitmq.port default=None
spring.amqp.rabbitmq.username default=None
== spring-boot-rabbitmq auto-configuration classes
org.springframework.boot.rabbitmq.autoconfigure.RabbitAutoConfiguration
org.springframework.boot.rabbitmq.autoconfigure.health.RabbitHealthContributorAutoConfiguration
org.springframework.boot.rabbitmq.autoconfigure.metrics.RabbitMetricsAutoConfiguration
== spring-boot-rabbitmq properties (selected spring.rabbitmq.*)
spring.rabbitmq.host default=localhost
spring.rabbitmq.password default=guest
spring.rabbitmq.port default=None
spring.rabbitmq.username default=guest
spring.rabbitmq.virtual-host default=None
== which Boot module wires RabbitMQ's AMQP 1.0 client (RabbitAmqpTemplate)?
spring-boot-amqp: auto-configuration classes mentioning RabbitAmqpTemplate: no
spring-boot-amqp-rabbitmq: auto-configuration classes mentioning RabbitAmqpTemplate: yes
spring-boot-rabbitmq: auto-configuration classes mentioning RabbitAmqpTemplate: no
+65
View File
@@ -0,0 +1,65 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>amqp10-spring-boot</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<java.version>25</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- In Boot 4.2 this starter means GENERIC AMQP 1.0 (protonj2 + spring-amqp-client, properties
under spring.amqp.*). The classic RabbitMQ 0-9-1 starter is spring-boot-starter-rabbitmq. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- The third Boot 4.2 AMQP starter: RabbitMQ's own AMQP 1.0 client (spring-rabbitmq-client),
properties under spring.amqp.rabbitmq.*. It auto-configures RabbitAmqpTemplate, RabbitAmqpAdmin
and a RabbitAmqpListenerContainerFactory; the classic 0-9-1 starter is spring-boot-starter-rabbitmq. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp-rabbitmq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-rabbitmq</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Prints what the two Boot 4.2.0 starters really contain, read straight from their jars
# (spring-configuration-metadata.json and the auto-configuration imports). Run after one mvn build
# so the jars are in ~/.m2.
set -eu
cd "$(dirname "$0")/.."
OUT=output/10-starter-comparison.txt
M2="${HOME}/.m2/repository"
BOOT=$(ls "$M2/org/springframework/boot/spring-boot-amqp" | sort -V | tail -1)
fetch() { # fetch <group-path> <artifact> <version> -> jar path (downloads via maven if missing)
local jar="$M2/$1/$2/$3/$2-$3.jar"
[ -f "$jar" ] || mvn -B -q dependency:get -Dartifact="$(echo "$1" | tr / .):$2:$3" >/dev/null
echo "$jar"
}
props() { # props <jar> <prefix-filter>
unzip -p "$1" META-INF/spring-configuration-metadata.json | python3 -c "
import json,sys
d=json.load(sys.stdin)
for p in d['properties']:
if p['name'].startswith('$2'):
print(' %-48s default=%s' % (p['name'], p.get('defaultValue')))"
}
{
echo "Spring Boot $BOOT"
for s in amqp amqp-rabbitmq rabbitmq; do
echo
echo "== spring-boot-starter-$s: description and dependencies"
pom="$M2/org/springframework/boot/spring-boot-starter-$s/$BOOT/spring-boot-starter-$s-$BOOT.pom"
[ -f "$pom" ] || mvn -B -q dependency:get -Dartifact="org.springframework.boot:spring-boot-starter-$s:$BOOT:pom" >/dev/null
grep -E '<description>|<artifactId>spring-boot-(amqp|amqp-rabbitmq|rabbitmq)<' "$pom" | sed 's/^ *//'
done
echo
echo "== spring-boot-amqp auto-configuration classes"
unzip -p "$(fetch org/springframework/boot spring-boot-amqp "$BOOT")" META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports | sed 's/^/ /'; echo
echo "== spring-boot-amqp properties (spring.amqp.*)"
props "$(fetch org/springframework/boot spring-boot-amqp "$BOOT")" spring.amqp.
echo
echo "== spring-boot-amqp-rabbitmq auto-configuration classes"
unzip -p "$(fetch org/springframework/boot spring-boot-amqp-rabbitmq "$BOOT")" META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports | sed 's/^/ /'; echo
echo "== spring-boot-amqp-rabbitmq properties (spring.amqp.rabbitmq.*)"
props "$(fetch org/springframework/boot spring-boot-amqp-rabbitmq "$BOOT")" spring.amqp.rabbitmq. | grep -E 'rabbitmq\.(host|port|username|password|address) '
echo
echo "== spring-boot-rabbitmq auto-configuration classes"
unzip -p "$(fetch org/springframework/boot spring-boot-rabbitmq "$BOOT")" META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports | sed 's/^/ /'; echo
echo "== spring-boot-rabbitmq properties (selected spring.rabbitmq.*)"
props "$(fetch org/springframework/boot spring-boot-rabbitmq "$BOOT")" spring.rabbitmq. | grep -E 'rabbitmq\.(host|port|username|password|virtual-host) '
echo
echo "== which Boot module wires RabbitMQ's AMQP 1.0 client (RabbitAmqpTemplate)?"
for j in spring-boot-amqp spring-boot-amqp-rabbitmq spring-boot-rabbitmq; do
n=$(unzip -p "$(fetch org/springframework/boot $j "$BOOT")" 'org/springframework/boot/*/autoconfigure/*AutoConfiguration*.class' 2>/dev/null | strings | grep -c 'RabbitAmqpTemplate' || true)
echo " $j: auto-configuration classes mentioning RabbitAmqpTemplate: $([ "$n" -gt 0 ] && echo yes || echo no)"
done
} > "$OUT"
cat "$OUT"
+10
View File
@@ -0,0 +1,10 @@
#!/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
@@ -0,0 +1,11 @@
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);
}
}
@@ -0,0 +1,27 @@
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;
}
}
@@ -0,0 +1,33 @@
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;
}
}
@@ -0,0 +1,5 @@
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) {
}
@@ -0,0 +1,54 @@
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();
}
}
@@ -0,0 +1,54 @@
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;
}
}
}
@@ -0,0 +1,6 @@
# 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
@@ -0,0 +1,25 @@
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();
}
}
@@ -0,0 +1,140 @@
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\"}");
}
}
@@ -0,0 +1,30 @@
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");
}
}
@@ -0,0 +1,105 @@
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();
}
}
}
@@ -0,0 +1,63 @@
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");
}
}
}
@@ -0,0 +1,81 @@
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());
}
}
}
@@ -0,0 +1,95 @@
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();
}
}
}
@@ -0,0 +1,82 @@
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();
}
}
}
@@ -0,0 +1,60 @@
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);
}
}
}
@@ -0,0 +1,61 @@
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);
}
}
}
@@ -0,0 +1,20 @@
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;
}
}
@@ -0,0 +1,37 @@
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);
}
}
}