SpringBoot--整合ActiveMQ

「爱情、让人受尽委屈。」 2021-08-24 15:59 645阅读 0赞

1. 创建项目,添加ActiveMQ依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-activemq</artifactId>
  4. </dependency>

2. 在application.properties中进行连接配置

  1. spring.activemq.broker-url=tcp://localhost:61616 #端口
  2. spring.activemq.packages.trust-all=true #信任所有的包
  3. spring.activemq.user=admin #用户名
  4. spring.activemq.password=admin #密码

编码

提供一个消息队列Bean,该Bean的实例就由ActiveMQ提供:

  1. @SpringBootApplication
  2. public class DemoApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(DemoApplication.class, args);
  5. }
  6. @Bean
  7. Queue queue(){
  8. return new ActiveMQQueue("amq");
  9. }
  10. }

创建一个JMS组件来完成消息的发送和接收:

  1. @Component
  2. public class JmsComponent {
  3. @Autowired
  4. JmsMessagingTemplate messagingTemplate;
  5. @Autowired
  6. Queue queue;
  7. public void send(Message msg){
  8. messagingTemplate.convertAndSend(this.queue, msg);
  9. }
  10. @JmsListener(destination = "amq")
  11. public void receive(Message msg){
  12. System.out.println("receive:" + msg);
  13. }
  14. }

4. 测试

  1. @Autowired
  2. JmsComponent jmsComponent;
  3. @Test
  4. public void test(){
  5. Message msg = new Message();
  6. msg.setContent("hello jms!");
  7. msg.setDate(new Date());
  8. jmsComponent.send(msg);
  9. }

控制台打印:

  1. receive:com.example.demo.pojo.Message@78a8611e

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,645人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot整合ActiveMQ

    前言   ActiveMQ 一个成熟的消息中间件,作用于系统之间的通信,降低模块与模块之间的耦合度。   消息的传递有两种类型: 1. Queue 队列模式:一个生