第一步:创建Maven项目
Maven依赖:
junit
junit
4.12
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-starter-activemq
2.2.6.RELEASE
org.springframework
spring-tx
5.2.5.RELEASE
org.springframework
spring-jms
5.2.5.RELEASE
org.apache.activemq
activemq-all
5.15.12
org.apache.activemq
activemq-pool
5.15.12
application.yml:
server:
port: 80
servlet:
context-path: /am
spring:
activemq:
broker-url: tcp://hcmaster:61616 #ActiveMQ服务器地址及端口
user: admin
password: admin
close-timeout: 5000
send-timeout: 3000
# 下面五行配置加上程序报错,程序启动不起来
# in-memory: false # true表示使用内置的MQ,false表示连接服务器
# pool:
# enabled: true # true表示使用连接池,false表示每发送一条数据就创建一个连接
# max-connections: 10 #连接池最大连接数
# idle-timeout: 30000 #空闲的连接过期时间,默认为30s
jms:
pub-sub-domain: false # 默认值false表示Queue,true表示Topic
queueName1: springboot-activemq-queue2
queueName2: springboot-activemq-queue2
# debug: true #显示Debug信息
第二步:生产者
@Service
public class Producer3 {
@Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
private JmsMessagingTemplate jmsTemplate;
// 发送消息,destination是发送到的队列,message是待发送的消息
public void sendMessage(Destination destination, final String message) {
jmsTemplate.convertAndSend(destination, message);
}
@JmsListener(destination="${queueName2}")
public void consumerMessage(String text){
System.out.println("从队列收到的回复报文为:"+text);
}
}
第三步:消费者
@Component
public class Consumer3 {
@JmsListener(destination = "${queueName1}")
@SendTo("${queueName2}")
public String receiveQueue(String text) {
System.out.println("Consumer3收到的消息为:" + text);
return "返回消息:" + text;
}
}
测试代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJmsApplicationTests {
@Value("${queueName1}")
private String queueName;
@Autowired
private Producer3 producer3;
@Test
public void contextLoads() {
Destination destination = new ActiveMQQueue(queueName);
producer3.sendMessage(destination, "请接收消息");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果: