# Quarkus JMS: typed destinations, listeners and XA without the boilerplate

## What JMS on Quarkus leaves to you today

If you use JMS on Quarkus today, you get a `ConnectionFactory` and not much else. Creating contexts and sessions, running consumer threads with a `receive()` loop, reconnecting after a failure, converting payloads: all of that is left to your application. Wiring XA transactions means combining the JMS session, pooled JMS, Narayana and, on the consumer side, a resource adapter.

Here is what a minimal order consumer looks like with only a `ConnectionFactory`:

```java
@ApplicationScoped
public class OrderConsumer implements Runnable {

    @Inject
    ConnectionFactory connectionFactory;

    @Inject
    ObjectMapper mapper;

    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private volatile boolean running = true;

    void onStart(@Observes StartupEvent ev) {
        executor.submit(this);
    }

    void onStop(@Observes ShutdownEvent ev) {
        running = false;
        executor.shutdown();
    }

    @Override
    public void run() {
        try (JMSContext context = connectionFactory.createContext(JMSContext.AUTO_ACKNOWLEDGE)) {
            JMSConsumer consumer = context.createConsumer(context.createQueue("orders"));
            while (running) {
                Message message = consumer.receive(1000);
                if (message == null) {
                    continue;
                }
                Order order = mapper.readValue(message.getBody(String.class), Order.class);
                process(order, message.getStringProperty("category"));
            }
        } catch (JMSException | JsonProcessingException e) {
            // From here on, nothing consumes "orders" until the application restarts
            Log.error("Order consumer stopped", e);
        }
    }

    void process(Order order, String category) {
        Log.infof("Processing %s order %s", category, order.id());
    }
}
```

That is about 40 lines, and it is still not production-ready. It runs a single consumer thread, it does not reconnect when the broker restarts, one malformed message stops consumption for good, and shutdown does not wait for the message being processed. Each of those is more code to write, test and maintain, in every application.

With Quarkus JMS, the same consumer is:

```java
@ApplicationScoped
public class OrderConsumer {

    @JmsListener("orders")
    void process(Order order, @JmsHeader("category") String category) {
        Log.infof("Processing %s order %s", category, order.id());
    }
}
```

The extension starts the consumer workers, converts the JSON payload, reconnects after a connection failure, and waits for in-flight messages on shutdown.

That listener is one piece of [Quarkus JMS](https://docs.quarkiverse.io/quarkus-jms/dev/index.html), a new Quarkiverse extension for Quarkus 4. The rest of the extension handles the remaining plumbing: typed destinations for sending and receiving, XA transactions through Narayana, and integration with OpenTelemetry, Micrometer and health checks.

Which part of it you use depends on your application:

- `JmsQueue<T>`, `JmsTopic<T>` and `@JmsListener`, when you want direct JMS semantics or migrate existing JMS or Jakarta EE code
- the `smallrye-jms` connector, when your application is built on Quarkus Messaging channels (`@Incoming` / `@Outgoing`)
- `quarkus-spring-jms`, if you are migrating from an application using Spring JMS and want to keep the same API.

## Where Quarkus JMS fits next to the existing JMS extensions

JMS support in Quarkus is spread across several extensions, and all of them work at the `ConnectionFactory` level. `quarkus-artemis-jms` and `quarkus-qpid-jms` provide the clients for Apache ActiveMQ Artemis and AMQP 1.0 brokers, `quarkus-pooled-jms` adds connection pooling, and `quarkus-ironjacamar` runs JCA resource adapters for MDB-style endpoints. For other providers, such as IBM MQ, you produce the `ConnectionFactory` bean yourself.

Quarkus JMS sits on top of whichever `ConnectionFactory` you have, and handles session management, payload conversion and the listener lifecycle:

![Quarkus JMS stack: three APIs on a shared runtime, optional pooled JMS and IronJacamar, and the providers that supply the ConnectionFactory](/assets/images/posts/quarkus-jms/quarkus-jms-stack.webp)

## Getting started with typed destinations and @JmsListener

Quarkus JMS requires Quarkus 4.0 or later. Add the extension next to your JMS provider, for example `quarkus-artemis-jms`:

```xml
<dependency>
    <groupId>io.quarkiverse.jms</groupId>
    <artifactId>quarkus-jms</artifactId>
    <version>0.4.1</version>
</dependency>
```

With `quarkus-artemis-jms`, Dev Services start an Artemis broker and configure the `ConnectionFactory`, so there is nothing else to set up.

The examples in this post exchange two records:

```java
public record Order(String id, String category) {
}

public record OrderEvent(String orderId, String status) {
}
```

Here is a REST endpoint that sends orders to a queue:

```java
import jakarta.inject.Inject;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;

import io.quarkiverse.jms.JmsQueue;
import io.smallrye.common.annotation.Identifier;

@Path("/orders")
public class OrderResource {

    @Inject
    @Identifier("orders")
    JmsQueue<Order> orders;

    @POST
    public void placeOrder(Order order) {
        orders.message(order)
              .property("category", order.category())
              .send();
    }
}
```

You can inject a destination by qualifying it with `@Identifier`. Injected destinations are type-safe: the generic parameter determines the payload type for both sending and receiving, and objects are converted to and from JSON using Jackson.

The listener from the introduction can do more than log. This version scales its consumers with the load and publishes a result:

```java
import jakarta.enterprise.context.ApplicationScoped;

import io.quarkiverse.jms.JmsHeader;
import io.quarkiverse.jms.JmsListener;
import io.quarkiverse.jms.SendTo;
import io.quarkus.logging.Log;

@ApplicationScoped
public class OrderProcessor {

    @JmsListener(value = "orders", concurrency = 2, maxConcurrency = 8)
    @SendTo("order-events")
    public OrderEvent process(Order order, @JmsHeader("category") String category) {
        Log.infof("Processing %s order %s", category, order.id());
        return new OrderEvent(order.id(), "accepted");
    }
}
```

The first non-annotated parameter is the message payload, and parameters annotated with `@JmsHeader` receive message properties. With `concurrency` and `maxConcurrency`, extra consumers are spawned when all existing ones are busy, and removed when they become idle. The `@SendTo` annotation sends the return value to another destination.

## Consume, write to the database and send in one XA transaction

XA transactions coordinate JMS message consumption with other XA resources, such as a database, in a single atomic transaction. XA needs an `XAConnectionFactory` from your provider and the `quarkus-narayana-jta` extension. With Artemis, enable XA on the connection factory and on the datasource:

```properties
quarkus.artemis.xa-enabled=true
quarkus.datasource.jdbc.transactions=xa
```

The [JMS providers page](https://docs.quarkiverse.io/quarkus-jms/dev/providers.html) shows the equivalent setting for other providers.

Then set the listener's acknowledge mode to `XA`:

```java
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;

import io.quarkiverse.jms.JmsClient;
import io.quarkiverse.jms.JmsListener;

@ApplicationScoped
public class OrderValidator {

    @Inject
    EntityManager em;

    @Inject
    JmsClient jms;

    @JmsListener(value = "incoming-orders", acknowledge = JmsListener.AcknowledgeMode.XA)
    public void validate(Order order) {
        em.persist(new AuditLog("validated", order.id()));
        jms.queue("validated-orders").send(order);
    }
}
```

`JmsClient` is an injectable service for accessing destinations dynamically at runtime, returning the same `JmsQueue` and `JmsTopic` instances described earlier. `AuditLog` is a JPA entity. If the method fails, the message stays on `incoming-orders`, the insert is rolled back, and nothing is sent to `validated-orders`.

The broker then redelivers the message, following its own redelivery policy. To keep a message that always fails from being redelivered forever, set a redelivery limit and a dead-letter address on the broker. The [extension docs](https://docs.quarkiverse.io/quarkus-jms/dev/quarkus-jms.html) also describe dead-letter routing from the application, with a `JmsListenerErrorHandler` bean.

Listener methods annotated with `@RunOnVirtualThread` run on virtual threads instead of the worker thread pool, which is useful for blocking I/O such as database calls or HTTP requests. Combined with XA and `maxConcurrency`, several messages are processed concurrently, each in its own virtual thread and transaction. In the `OrderValidator` above, this takes one more annotation, `io.smallrye.common.annotation.RunOnVirtualThread`:

```java
@JmsListener(value = "incoming-orders", acknowledge = JmsListener.AcknowledgeMode.XA, maxConcurrency = 16)
@RunOnVirtualThread
public void validate(Order order) {
    em.persist(new AuditLog("validated", order.id()));
    jms.queue("validated-orders").send(order);
}
```

### Why not pooled JMS and @Transactional?

Before Quarkus JMS, the usual way to get XA was `quarkus-pooled-jms` with `quarkus.pooled-jms.transaction=xa`. The pool enlists its sessions in the current JTA transaction, so a `@Transactional` method that creates a `JMSContext` sends and receives as part of that transaction.

That works well for sending. Consuming is where it gets harder: there is no listener to put `@Transactional` on, so you either run your own `receive()` loop and demarcate each transaction by hand, or deploy a JCA resource adapter with IronJacamar. With Quarkus JMS, the listener itself is the transaction boundary, and the same XA support applies to `JmsClient` calls inside your own `@Transactional` methods.

The two XA models do not mix. Quarkus JMS enlists sessions directly through the `XAConnectionFactory`, so if you keep `quarkus-pooled-jms` alongside XA listeners, set `quarkus.pooled-jms.transaction=disabled` and let the pool handle connections only.

## Tracing, health checks and fault tolerance on listeners

Quarkus JMS integrates with other Quarkus extensions when they are present:

- Observability extensions such as `quarkus-opentelemetry` and `quarkus-micrometer` allow tracing and timing sends, receives and listener invocations. Trace context is propagated in message properties.
- When `quarkus-smallrye-health` is available, a readiness check reports whether listeners are connected.
- The fault-tolerance annotations such as `@Retry`, `@CircuitBreaker` and `@Fallback` work on listener methods when `quarkus-smallrye-fault-tolerance` is available.

Consult the [extension docs](https://docs.quarkiverse.io/quarkus-jms/dev/index.html) to discover other features such as session pooling, request-reply, queue browsing, durable subscriptions, selectors, dead-letter routing, runtime listener registration and graceful shutdown.

## The Quarkus Messaging connector, now tested with Quarkus

The `smallrye-jms` connector for `@Incoming` / `@Outgoing` channels comes from SmallRye Reactive Messaging, but Quarkus never shipped an extension for it. The new `quarkus-messaging-jms` extension, part of this project, makes it a Quarkus extension that is compatible and tested with Quarkus. If you used the connector by adding the SmallRye artifact directly, replace it with `io.quarkiverse.jms:quarkus-messaging-jms`.

The connector also gained local and XA transactions, selected with the `transaction-mode` attribute, and failure strategies such as `fail`, `ignore` and `dead-letter-queue`.

## Supported JMS providers

Quarkus JMS works with any provider that exposes a `ConnectionFactory` bean. Besides Apache ActiveMQ Artemis, it is tested with:

- Apache ActiveMQ Classic
- AMQP 1.0 brokers, through `quarkus-qpid-jms`
- IBM MQ
- RabbitMQ
- Amazon SQS and Oracle AQ, which only implement JMS 1.1, through a compatibility mode that does not support XA

The [JMS providers page](https://docs.quarkiverse.io/quarkus-jms/dev/providers.html) shows how to configure each of them.

Quarkus JMS works in native executables, as long as the JMS client does. `quarkus-artemis-jms` and `quarkus-qpid-jms` both support native compilation.

## Using Quarkus JMS with pooled JMS, IronJacamar and Camel

Quarkus JMS uses the default CDI `ConnectionFactory` bean, or a named one qualified with `@Identifier`, so it works on top of the extensions you already use.

When you need multiple connections or JMX monitoring, add `quarkus-pooled-jms`: the built-in session pool is then disabled automatically. If you also use XA listeners, set `quarkus.pooled-jms.transaction=disabled`, as explained in the XA section above.

When `quarkus-ironjacamar` is present, `@JmsListener` methods on classes annotated with `@ResourceEndpoint` are activated through the JCA resource adapter instead of the default polling consumer. Camel Quarkus routes are not affected and can share the same `ConnectionFactory`.

## Migrating to Quarkus JMS

If your application already uses JMS through a `ConnectionFactory`, the [migration guide](https://docs.quarkiverse.io/quarkus-jms/dev/migration.html) shows how to replace the code that manages contexts, sessions and consumer threads with `JmsQueue` and `@JmsListener`. It also covers moving JCA message endpoints to `@JmsListener`.

### Spring JMS compatibility

The `quarkus-spring-jms` module lets you use the Spring JMS API in a Quarkus application. It maps Spring's `@JmsListener`, `@SendTo`, `@Header`, `JmsClient` and `JmsResponse` to their Quarkus JMS equivalents at build time, so existing Spring listeners need minimal changes:

```java
import jakarta.enterprise.context.ApplicationScoped;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.SendTo;

@ApplicationScoped
public class OrderListener {

    @JmsListener(destination = "orders", concurrency = "3-5")
    @SendTo("order-events")
    public OrderEvent process(Order order, @Header("category") String category) {
        return new OrderEvent(order.id(), "processed");
    }
}
```

Container factories are configured in `application.properties` instead of `@Bean` definitions. Session pooling, transactions, tracing, metrics and health checks apply to Spring-annotated listeners as well. See the [Spring JMS compatibility guide](https://docs.quarkiverse.io/quarkus-jms/dev/spring-jms.html) for details.

## Known limitations in the preview

Quarkus JMS is in preview: it is experimental, and we are waiting for feedback before declaring it stable. Before you adopt it, keep in mind:

- APIs and configuration properties may still change between releases, based on that feedback.
- XA requires an `XAConnectionFactory`, and is not available in the JMS 1.1 compatibility mode used for Amazon SQS and Oracle AQ.
- XA listeners do not work with the XA enlistment of `quarkus-pooled-jms`. Set `quarkus.pooled-jms.transaction=disabled` when you use both.
- Typed destinations convert payloads to and from JSON with Jackson, and add the payload type in a `_type` message property. For other formats, build the JMS message yourself with `send(ctx -> ...)`.
- Native compilation depends on your JMS client. It is supported with `quarkus-artemis-jms` and `quarkus-qpid-jms`.

## Try it and tell us which broker you use

Quarkus JMS will be part of the Quarkus Platform. To try it, follow the [Getting Started guide](https://docs.quarkiverse.io/quarkus-jms/dev/index.html). We would like your feedback, in particular on the providers you use and on migrating existing applications.

You can reach us on [Zulip](https://quarkusio.zulipchat.com) or open an issue on [GitHub](https://github.com/quarkiverse/quarkus-jms/issues).
