首页 > 其他分享 >SpringBoot(七)

SpringBoot(七)

时间:2023-03-28 23:24:09浏览次数:35  
标签:SpringBoot id topic 端点 监控 服务器 public

③SpringBoot整合ActiveMQ

老古董产品,目前市面上用的很少

windows版安装包下载地址:https://activemq.apache.org/components/classic/download/

运行bin目录下的win32或win64目录下的activemq.bat命令即可,根据自己的操作系统选择即可,默认对外服务端口61616。

web管理服务默认端口8161

  1. 导入springboot整合ActiveMQ的starter

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>
    
  2. 配置ActiveMQ的服务器地址

    spring:
      activemq:
        broker-url: tcp://localhost:61616
    
  3. 使用JmsMessagingTemplate操作ActiveMQ

    @Service
    public class MessageServiceActivemqImpl implements MessageService {
        @Autowired
        private JmsMessagingTemplate messagingTemplate;
    
        @Override
        public void sendMessage(String id) {
            //发送消息需要先将消息的类型转换成字符串,然后再发送,所以是convertAndSend,定义消息发送的位置,和具体的消息内容,此处使用id作为消息内容。
            System.out.println("待发送短信的订单已纳入处理队列,id:"+id);
            messagingTemplate.convertAndSend("order.queue.id",id);
        }
    
        @Override
        public String doMessage() {
            //接收消息需要先将消息接收到,然后再转换成指定的数据类型,所以是receiveAndConvert,接收消息除了提供读取的位置,还要给出转换后的数据的具体类型。
            String id = messagingTemplate.receiveAndConvert("order.queue.id",String.class);
            System.out.println("已完成短信发送业务,id:"+id);
            return id;
        }
    }
    
  4. 使用消息监听器在服务器启动后,监听指定位置,当消息出现后,立即消费消息

    @Component
    public class MessageListener {
        //使用注解@JmsListener定义当前方法监听ActiveMQ中指定名称的消息队列。
        @JmsListener(destination = "order.queue.id")
        //如果当前消息队列处理完还需要继续向下传递当前消息到另一个队列中使用注解@SendTo即可,这样即可构造连续执行的顺序消息队列。
        @SendTo("order.other.queue.id")
        public String receive(String id){
            System.out.println("已完成短信发送业务,id:"+id);
            return "new:"+id;
        }
    }
    
  5. 切换消息模型由点对点模型到发布订阅模型,修改jms配置即可

    spring:
      activemq:
        broker-url: tcp://localhost:61616
      jms:
      #pub-sub-domain默认值为false,即点对点模型,修改为true后就是发布订阅模型。
        pub-sub-domain: true
    

④SpringBoot整合RabbitMQ

RabbitMQ是MQ产品中的目前较为流行的产品之一,它遵从AMQP协议。RabbitMQ的底层实现语言使用的是Erlang,所以安装RabbitMQ需要先安装Erlang。

安装

Erlang的windows版安装包下载地址:https

标签:SpringBoot,id,topic,端点,监控,服务器,public
From: https://www.cnblogs.com/Myvlog/p/17267162.html

相关文章