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
@@ -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);
}
}
}