ActiveMQ

SpringBoot整合ActiveMQ

pom.xml

1
2
3
4
5
6
7
<!-- pom.xml增加依赖-->
<!-- activemq所对JMS的支持,整合Spring和Activemq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>

application.yml

1
2
3
4
5
6
7
8
9
#application.yml
spring:
activemq:
broker-url: tcp://192.168.1.132:61616
user: admin
password: admin
jms:
#fasle = Queue true = Topic 默认Queue
pub-sub-domain: false

Bean

1
2
3
4
5
6
7
8
9
10
11
12
13
@Component
@EnableJms //开启SpringBoot对Jms的支持
public class ConfigBean {
@Bean
public Queue queue() {
return new ActiveMQQueue("myQueueName");
}

@Bean
public Topic topic() {
return new ActiveMQTopic("myTopicName");
}
}

生产者-定时调度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Component
public class Queue_Produce {
@Autowired
private JmsMessagingTemplate jmsMessagingTmplate;
@Autowired
private Queue queue;
//@Autowired
//private Topic topic;

public void produceMsg() {
//convertAndSend自动转换消息的类型
jmsMessagingTemplate.convertAndSend(queue,"SpringBoot队列发送消息");
//jmsMessagingTemplate.convertAndSend(topic,"SpringBoot主题发送消息");
}

//间隔3秒定投
@Scheduled(fixedDelay = 3000)
public void produceMsgScheduled() {
jmsMessagingTemplate.convertAndSend(queue,"SpringBoot定时投递消息");
}
}
1
2
3
4
5
6
7
@SpringBootApplication
@EnableScheduling //激活定时调度
public class MainApp_Produce {
public static void main(String[] args) {
SpringApplication.run(MainApp_Produce.class, args);
}
}

Junits

1
2
3
4
5
6
7
8
9
10
11
12
13
//单元测试执行
@SpringBootTest(classes = MainApp_Produce.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestActiveMQ {
@Autowired
private Queue_Produce queue_produce;

@Test
public void testSend() throws Exception {
queue_produce.produceMsg();
}
}

消费者-监听器

1
2
3
4
5
6
7
8
@Component
public class Queue_Consumer {
//设置监听器
@JmsListener(destination = "myQueueName")
public void receive(TextMessage textMessage) throws JMSException {
System.out.println("消费者收到消息:" + textMessage.getText());
}
}

最后更新: 2020年11月12日 12:21

原始链接: https://midkuro.gitee.io/2020/05/23/activemq-springboot/

× 请我吃糖~
打赏二维码