Linux 拨号vps windows公众号手机端

SpringBoot中怎么发布和订阅消息

lewis 7年前 (2018-04-04) 阅读数 11 #程序编程
文章标签 springboot

在SpringBoot中,可以使用Spring的消息队列框架来发布和订阅消息。其中,常用的消息队列框架包括RabbitMQ、ActiveMQ、Kafka等。下面以RabbitMQ为例介绍如何在SpringBoot中发布和订阅消息:

  1. 添加依赖: 首先需要在pom.xml文件中添加RabbitMQ的依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. 配置RabbitMQ: 在application.propertiesapplication.yml中添加RabbitMQ的配置信息:
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
  1. 发布消息: 创建一个消息发送者类,并使用RabbitTemplate来发送消息。例如:
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessageSender {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void sendMessage(String message) {
        rabbitTemplate.convertAndSend("exchange", "routing-key", message);
    }
}
  1. 订阅消息: 创建一个消息接收者类,并使用@RabbitListener注解来接收消息。例如:
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class MessageReceiver {
    @RabbitListener(queues = "queue-name")
    public void receiveMessage(String message) {
        System.out.println("Received message: " + message);
    }
}

通过以上步骤,就可以在SpringBoot中实现发布和订阅消息了。当消息发送者调用sendMessage方法时,消息接收者会收到消息并输出到控制台。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门