如何在Spring Boot 3中为ActiveMQ Artemis 2.28.0队列设置过期地址
在Spring Boot 3中为ActiveMQ Artemis自动创建的队列设置过期地址
不需要修改broker.xml,你可以通过以下几种方式在Spring Boot应用内配置队列的过期地址:
方法1:利用Artemis Core API手动创建队列
如果你的应用连接外部Artemis broker,或者需要更灵活的配置,可以通过Core API直接创建队列并指定过期地址:
import jakarta.jms.JMSContext; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import jakarta.annotation.PostConstruct; @Configuration public class ArtemisQueueConfig { @Autowired private JMSContext jmsContext; @PostConstruct public void createQueueWithExpiry() throws Exception { // 从JMSContext转换获取Core Session ClientSession coreSession = jmsContext.createSession().unwrap(ClientSession.class); // 定义队列配置,指定过期地址 QueueConfiguration queueConfig = new QueueConfiguration("myQueue") .setAddress("myQueue") .setExpiryAddress("expiryQueue"); // 设置过期消息转发的目标地址 // 队列不存在时创建 if (!coreSession.queueQuery(queueConfig.getName()).isExists()) { coreSession.createQueue(queueConfig); } // 创建过期地址对应的队列(按需) QueueConfiguration expiryQueueConfig = new QueueConfiguration("expiryQueue") .setAddress("expiryQueue"); if (!coreSession.queueQuery(expiryQueueConfig.getName()).isExists()) { coreSession.createQueue(expiryQueueConfig); } } }
方法2:嵌入式Broker的配置属性(适用于内嵌Artemis)
如果你的Spring Boot应用使用嵌入式ActiveMQ Artemis,可以直接在配置文件中定义地址规则,自动关联队列的过期地址:
application.properties
# 配置目标队列地址的过期地址 spring.artemis.embedded.server.address-settings.myQueue.expiry-address=expiryQueue # 可选:设置消息过期延迟时间(单位:毫秒) spring.artemis.embedded.server.address-settings.myQueue.expiry-delay=3600000
application.yaml
spring: artemis: embedded: server: address-settings: myQueue: expiry-address: expiryQueue expiry-delay: 3600000 # 1小时后消息过期
这种方式会在嵌入式broker启动时自动应用地址配置,应用创建myQueue队列时会自动继承该地址的过期规则。
方法3:通过Spring Bean定义队列并附加属性
如果你习惯用Spring的@Bean定义队列,可以使用Artemis的JMS客户端类结合核心配置设置:
import org.apache.activemq.artemis.jms.client.ActiveMQQueue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class QueueBeanConfig { @Bean public ActiveMQQueue myQueue() { ActiveMQQueue queue = new ActiveMQQueue("myQueue"); // 为队列配置过期地址 queue.getQueueConfiguration().setExpiryAddress("expiryQueue"); return queue; } @Bean public ActiveMQQueue expiryQueue() { return new ActiveMQQueue("expiryQueue"); } }
注意:如果连接外部broker,需要确认broker.xml中address-settings的allow-client-address-settings属性为true(默认值为true,若被修改过需检查)。
内容的提问来源于stack exchange,提问作者mathieu deschamps
相关产品推荐
相关产品推荐

