The Spring Framework provides extensive support for integrating with messaging systems, from simplified use of the JMS API using JmsTemplate to a complete infrastructure to receive messages asynchronously.
Spring AMQP provides a similar feature set for the Advanced Message Queuing Protocol.
Spring Boot also provides auto-configuration options for RabbitTemplate and RabbitMQ.
Spring WebSocket natively includes support for STOMP messaging, and Spring Boot has support for that through starters and a small amount of auto-configuration.
Spring Boot also has support for Apache Kafka.
1. JMS
The jakarta.jms.ConnectionFactory interface provides a standard method of creating a jakarta.jms.Connection for interacting with a JMS broker.
Although Spring needs a ConnectionFactory to work with JMS, you generally need not use it directly yourself and can instead rely on higher level messaging abstractions.
(See the relevant section of the Spring Framework reference documentation for details.)
Spring Boot also auto-configures the necessary infrastructure to send and receive messages.
1.1. ActiveMQ Artemis Support
Spring Boot can auto-configure a ConnectionFactory when it detects that ActiveMQ Artemis is available on the classpath.
If the broker is present, an embedded broker is automatically started and configured (unless the mode property has been explicitly set).
The supported modes are embedded (to make explicit that an embedded broker is required and that an error should occur if the broker is not available on the classpath) and native (to connect to a broker using the netty transport protocol).
When the latter is configured, Spring Boot configures a ConnectionFactory that connects to a broker running on the local machine with the default settings.
If you use spring-boot-starter-artemis, the necessary dependencies to connect to an existing ActiveMQ Artemis instance are provided, as well as the Spring infrastructure to integrate with JMS.
Adding org.apache.activemq:artemis-jakarta-server to your application lets you use embedded mode.
|
ActiveMQ Artemis configuration is controlled by external configuration properties in spring.artemis.*.
For example, you might declare the following section in application.properties:
spring.artemis.mode=native
spring.artemis.broker-url=tcp://192.168.1.210:9876
spring.artemis.user=admin
spring.artemis.password=secret
spring:
artemis:
mode: native
broker-url: "tcp://192.168.1.210:9876"
user: "admin"
password: "secret"
When embedding the broker, you can choose if you want to enable persistence and list the destinations that should be made available.
These can be specified as a comma-separated list to create them with the default options, or you can define bean(s) of type org.apache.activemq.artemis.jms.server.config.JMSQueueConfiguration or org.apache.activemq.artemis.jms.server.config.TopicConfiguration, for advanced queue and topic configurations, respectively.
By default, a CachingConnectionFactory wraps the native ConnectionFactory with sensible settings that you can control by external configuration properties in spring.jms.*:
spring.jms.cache.session-cache-size=5
spring:
jms:
cache:
session-cache-size: 5
If you’d rather use native pooling, you can do so by adding a dependency on org.messaginghub:pooled-jms and configuring the JmsPoolConnectionFactory accordingly, as shown in the following example:
spring.artemis.pool.enabled=true
spring.artemis.pool.max-connections=50
spring:
artemis:
pool:
enabled: true
max-connections: 50
See ArtemisProperties for more supported options.
No JNDI lookup is involved, and destinations are resolved against their names, using either the name attribute in the Artemis configuration or the names provided through configuration.
1.2. Using a JNDI ConnectionFactory
If you are running your application in an application server, Spring Boot tries to locate a JMS ConnectionFactory by using JNDI.
By default, the java:/JmsXA and java:/XAConnectionFactory location are checked.
You can use the spring.jms.jndi-name property if you need to specify an alternative location, as shown in the following example:
spring.jms.jndi-name=java:/MyConnectionFactory
spring:
jms:
jndi-name: "java:/MyConnectionFactory"
1.3. Sending a Message
Spring’s JmsTemplate is auto-configured, and you can autowire it directly into your own beans, as shown in the following example:
@Component
public class MyBean {
private final JmsTemplate jmsTemplate;
public MyBean(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
}
@Component
class MyBean(private val jmsTemplate: JmsTemplate) {
}
JmsMessagingTemplate can be injected in a similar manner.
If a DestinationResolver or a MessageConverter bean is defined, it is associated automatically to the auto-configured JmsTemplate.
|
1.4. Receiving a Message
When the JMS infrastructure is present, any bean can be annotated with @JmsListener to create a listener endpoint.
If no JmsListenerContainerFactory has been defined, a default one is configured automatically.
If a DestinationResolver, a MessageConverter, or a jakarta.jms.ExceptionListener beans are defined, they are associated automatically with the default factory.
By default, the default factory is transactional.
If you run in an infrastructure where a JtaTransactionManager is present, it is associated to the listener container by default.
If not, the sessionTransacted flag is enabled.
In that latter scenario, you can associate your local data store transaction to the processing of an incoming message by adding @Transactional on your listener method (or a delegate thereof).
This ensures that the incoming message is acknowledged, once the local transaction has completed.
This also includes sending response messages that have been performed on the same JMS session.
The following component creates a listener endpoint on the someQueue destination:
@Component
public class MyBean {
@JmsListener(destination = "someQueue")
public void processMessage(String content) {
// ...
}
}
@Component
class MyBean {
@JmsListener(destination = "someQueue")
fun processMessage(content: String?) {
// ...
}
}
See the Javadoc of @EnableJms for more details.
|
If you need to create more JmsListenerContainerFactory instances or if you want to override the default, Spring Boot provides a DefaultJmsListenerContainerFactoryConfigurer that you can use to initialize a DefaultJmsListenerContainerFactory with the same settings as the one that is auto-configured.
For instance, the following example exposes another factory that uses a specific MessageConverter:
@Configuration(proxyBeanMethods = false)
public class MyJmsConfiguration {
@Bean
public DefaultJmsListenerContainerFactory myFactory(DefaultJmsListenerContainerFactoryConfigurer configurer) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
ConnectionFactory connectionFactory = getCustomConnectionFactory();
configurer.configure(factory, connectionFactory);
factory.setMessageConverter(new MyMessageConverter());
return factory;
}
private ConnectionFactory getCustomConnectionFactory() {
return ...
}
}
@Configuration(proxyBeanMethods = false)
class MyJmsConfiguration {
@Bean
fun myFactory(configurer: DefaultJmsListenerContainerFactoryConfigurer): DefaultJmsListenerContainerFactory {
val factory = DefaultJmsListenerContainerFactory()
val connectionFactory = getCustomConnectionFactory()
configurer.configure(factory, connectionFactory)
factory.setMessageConverter(MyMessageConverter())
return factory
}
fun getCustomConnectionFactory() : ConnectionFactory? {
return ...
}
}
Then you can use the factory in any @JmsListener-annotated method as follows:
@Component
public class MyBean {
@JmsListener(destination = "someQueue", containerFactory = "myFactory")
public void processMessage(String content) {
// ...
}
}
@Component
class MyBean {
@JmsListener(destination = "someQueue", containerFactory = "myFactory")
fun processMessage(content: String?) {
// ...
}
}
2. AMQP
The Advanced Message Queuing Protocol (AMQP) is a platform-neutral, wire-level protocol for message-oriented middleware.
The Spring AMQP project applies core Spring concepts to the development of AMQP-based messaging solutions.
Spring Boot offers several conveniences for working with AMQP through RabbitMQ, including the spring-boot-starter-amqp “Starter”.
2.1. RabbitMQ Support
RabbitMQ is a lightweight, reliable, scalable, and portable message broker based on the AMQP protocol. Spring uses RabbitMQ to communicate through the AMQP protocol.
RabbitMQ configuration is controlled by external configuration properties in spring.rabbitmq.*.
For example, you might declare the following section in application.properties:
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=secret
spring:
rabbitmq:
host: "localhost"
port: 5672
username: "admin"
password: "secret"
Alternatively, you could configure the same connection using the addresses attribute:
spring.rabbitmq.addresses=amqp://admin:secret@localhost
spring:
rabbitmq:
addresses: "amqp://admin:secret@localhost"
When specifying addresses that way, the host and port properties are ignored.
If the address uses the amqps protocol, SSL support is enabled automatically.
|
See RabbitProperties for more of the supported property-based configuration options.
To configure lower-level details of the RabbitMQ ConnectionFactory that is used by Spring AMQP, define a ConnectionFactoryCustomizer bean.
If a ConnectionNameStrategy bean exists in the context, it will be automatically used to name connections created by the auto-configured CachingConnectionFactory.
| See Understanding AMQP, the protocol used by RabbitMQ for more details. |
2.2. Sending a Message
Spring’s AmqpTemplate and AmqpAdmin are auto-configured, and you can autowire them directly into your own beans, as shown in the following example:
@Component
public class MyBean {
private final AmqpAdmin amqpAdmin;
private final AmqpTemplate amqpTemplate;
public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
this.amqpAdmin = amqpAdmin;
this.amqpTemplate = amqpTemplate;
}
}
@Component
class MyBean(private val amqpAdmin: AmqpAdmin, private val amqpTemplate: AmqpTemplate) {
}
RabbitMessagingTemplate can be injected in a similar manner.
If a MessageConverter bean is defined, it is associated automatically to the auto-configured AmqpTemplate.
|
If necessary, any org.springframework.amqp.core.Queue that is defined as a bean is automatically used to declare a corresponding queue on the RabbitMQ instance.
To retry operations, you can enable retries on the AmqpTemplate (for example, in the event that the broker connection is lost):
spring.rabbitmq.template.retry.enabled=true
spring.rabbitmq.template.retry.initial-interval=2s
spring:
rabbitmq:
template:
retry:
enabled: true
initial-interval: "2s"
Retries are disabled by default.
You can also customize the RetryTemplate programmatically by declaring a RabbitRetryTemplateCustomizer bean.
If you need to create more RabbitTemplate instances or if you want to override the default, Spring Boot provides a RabbitTemplateConfigurer bean that you can use to initialize a RabbitTemplate with the same settings as the factories used by the auto-configuration.
2.3. Sending a Message To A Stream
To send a message to a particular stream, specify the name of the stream, as shown in the following example:
spring.rabbitmq.stream.name=my-stream
spring:
rabbitmq:
stream:
name: "my-stream"
If a MessageConverter, StreamMessageConverter, or ProducerCustomizer bean is defined, it is associated automatically to the auto-configured RabbitStreamTemplate.
If you need to create more RabbitStreamTemplate instances or if you want to override the default, Spring Boot provides a RabbitStreamTemplateConfigurer bean that you can use to initialize a RabbitStreamTemplate with the same settings as the factories used by the auto-configuration.
2.4. Receiving a Message
When the Rabbit infrastructure is present, any bean can be annotated with @RabbitListener to create a listener endpoint.
If no RabbitListenerContainerFactory has been defined, a default SimpleRabbitListenerContainerFactory is automatically configured and you can switch to a direct container using the spring.rabbitmq.listener.type property.
If a MessageConverter or a MessageRecoverer bean is defined, it is automatically associated with the default factory.
The following sample component creates a listener endpoint on the someQueue queue:
@Component
public class MyBean {
@RabbitListener(queues = "someQueue")
public void processMessage(String content) {
// ...
}
}
@Component
class MyBean {
@RabbitListener(queues = ["someQueue"])
fun processMessage(content: String?) {
// ...
}
}
See the Javadoc of @EnableRabbit for more details.
|
If you need to create more RabbitListenerContainerFactory instances or if you want to override the default, Spring Boot provides a SimpleRabbitListenerContainerFactoryConfigurer and a DirectRabbitListenerContainerFactoryConfigurer that you can use to initialize a SimpleRabbitListenerContainerFactory and a DirectRabbitListenerContainerFactory with the same settings as the factories used by the auto-configuration.
| It does not matter which container type you chose. Those two beans are exposed by the auto-configuration. |
For instance, the following configuration class exposes another factory that uses a specific MessageConverter:
@Configuration(proxyBeanMethods = false)
public class MyRabbitConfiguration {
@Bean
public SimpleRabbitListenerContainerFactory myFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
ConnectionFactory connectionFactory = getCustomConnectionFactory();
configurer.configure(factory, connectionFactory);
factory.setMessageConverter(new MyMessageConverter());
return factory;
}
private ConnectionFactory getCustomConnectionFactory() {
return ...
}
}
@Configuration(proxyBeanMethods = false)
class MyRabbitConfiguration {
@Bean
fun myFactory(configurer: SimpleRabbitListenerContainerFactoryConfigurer): SimpleRabbitListenerContainerFactory {
val factory = SimpleRabbitListenerContainerFactory()
val connectionFactory = getCustomConnectionFactory()
configurer.configure(factory, connectionFactory)
factory.setMessageConverter(MyMessageConverter())
return factory
}
fun getCustomConnectionFactory() : ConnectionFactory? {
return ...
}
}
Then you can use the factory in any @RabbitListener-annotated method, as follows:
@Component
public class MyBean {
@RabbitListener(queues = "someQueue", containerFactory = "myFactory")
public void processMessage(String content) {
// ...
}
}
@Component
class MyBean {
@RabbitListener(queues = ["someQueue"], containerFactory = "myFactory")
fun processMessage(content: String?) {
// ...
}
}
You can enable retries to handle situations where your listener throws an exception.
By default, RejectAndDontRequeueRecoverer is used, but you can define a MessageRecoverer of your own.
When retries are exhausted, the message is rejected and either dropped or routed to a dead-letter exchange if the broker is configured to do so.
By default, retries are disabled.
You can also customize the RetryTemplate programmatically by declaring a RabbitRetryTemplateCustomizer bean.
By default, if retries are disabled and the listener throws an exception, the delivery is retried indefinitely.
You can modify this behavior in two ways: Set the defaultRequeueRejected property to false so that zero re-deliveries are attempted or throw an AmqpRejectAndDontRequeueException to signal the message should be rejected.
The latter is the mechanism used when retries are enabled and the maximum number of delivery attempts is reached.
|
3. Apache Kafka Support
Apache Kafka is supported by providing auto-configuration of the spring-kafka project.
Kafka configuration is controlled by external configuration properties in spring.kafka.*.
For example, you might declare the following section in application.properties:
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup
spring:
kafka:
bootstrap-servers: "localhost:9092"
consumer:
group-id: "myGroup"
To create a topic on startup, add a bean of type NewTopic.
If the topic already exists, the bean is ignored.
|
See KafkaProperties for more supported options.
3.1. Sending a Message
Spring’s KafkaTemplate is auto-configured, and you can autowire it directly in your own beans, as shown in the following example:
@Component
public class MyBean {
private final KafkaTemplate<String, String> kafkaTemplate;
public MyBean(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
}
@Component
class MyBean(private val kafkaTemplate: KafkaTemplate<String, String>) {
}
If the property spring.kafka.producer.transaction-id-prefix is defined, a KafkaTransactionManager is automatically configured.
Also, if a RecordMessageConverter bean is defined, it is automatically associated to the auto-configured KafkaTemplate.
|
3.2. Receiving a Message
When the Apache Kafka infrastructure is present, any bean can be annotated with @KafkaListener to create a listener endpoint.
If no KafkaListenerContainerFactory has been defined, a default one is automatically configured with keys defined in spring.kafka.listener.*.
The following component creates a listener endpoint on the someTopic topic: