第一步:创建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
queueName: springboot-activemq-queue
# debug: true #显示Debug信息
第二步:队列生产者消费者
1. 创建Producer
@Service
public class Producer {
@Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
private JmsMessagingTemplate jmsTemplate;
// 发送消息,destination是发送到的队列,message是待发送的消息
public void sendMessage(Destination destination, final String message) {
jmsTemplate.convertAndSend(destination, message);
}
}
2. 创建Consumer
@Component
public class Consumer {
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener(destination = "${queueName}")
public void receiveQueue(String text) {
System.out.println("Consumer收到的消息为:" + text);
}
}
3.测试代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJmsApplicationTests {
@Value("${queueName}")
private String queueName;
@Autowired
private Producer producer;
@Test
public void contextLoads() {
Destination destination = new ActiveMQQueue(queueName);
for(int i=0; i
关注
打赏