必须使用Spring Boot 3.0+、JDK 17+,配置native模式连接Artemis Core协议端口61616,显式声明Queue Bean,用JmsTemplate.send()或convertAndSend()发送,receiveAndConvert()同步接收。

要在Spring Boot项目中使用3.0版本的spring-boot-starter-artemis实现传统JMS消息传递(即基于Queue的点对点模型),必须确保依赖版本与Artemis服务端协议兼容,且连接参数与broker实际监听配置严格匹配,否则会抛出Connection refused或Invalid destination异常。
添加3.0版本Starter依赖
打开pom.xml,在<dependencies></dependencies>区块内添加以下依赖:
注意:Spring Boot 3.x要求JDK 17+,若项目仍用JDK 8或11,【必须降级到2.7.x系列starter】,否则编译失败。
配置Artemis连接参数
在application.yml中写入以下配置:
spring:
artemis:
mode: native
host: localhost
port: 61616
user: admin
password: admin
该配置启用原生Netty协议连接本地Artemis broker。若broker启用了AMQP或STOMP协议端口,此处不能复用——【native模式只认OpenWire或Core协议端口】,默认61616即Core协议监听端口。
声明JMS Queue目的地
创建一个@Configuration类,注入Queue Bean:
@Bean
public Queue exampleQueue() {
return new ActiveMQQueue("example.queue");
}
这一步不可省略。Spring Boot 3.0不再自动注册默认队列,未显式声明会导致JmsTemplate.send()抛出DestinationResolutionException。
使用JmsTemplate发送消息
方法一:直接注入JmsTemplate并调用send()
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private Queue exampleQueue;
public void sendMessage() {
jmsTemplate.send(exampleQueue, session → session.createTextMessage("Hello Artemis"));
}
方法二:使用lambda简化构造(推荐)
jmsTemplate.convertAndSend("example.queue", "Hello Artemis");
注意:convertAndSend内部会尝试解析字符串为目标Queue,但仅当destination resolver启用且broker存在同名队列时才成功;生产环境务必用第一种方式绑定明确的Queue Bean。
同步接收消息
第一步:注入JmsTemplate
第二步:调用receive()方法指定超时时间
String msg = jmsTemplate.receiveAndConvert("example.queue", 5000);
第三步:处理返回值
if (msg != null) {
System.out.println("收到:" + msg);
} else {
System.out.println("超时未收到消息");
}
receiveAndConvert()底层调用的是同步阻塞接收,超时后返回null,不会抛异常。若需严格保障消息必达,应改用MessageListenerContainer配合@JmsListener注解。

















