在SpringBoot中,可以使用Spring的消息隊列框架來發布和訂閱消息。其中,常用的消息隊列框架包括RabbitMQ、ActiveMQ、Kafka等。下面以RabbitMQ為例介紹如何在SpringBoot中發布和訂閱消息:
pom.xml
文件中添加RabbitMQ的依賴:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.properties
或application.yml
中添加RabbitMQ的配置信息:spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
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);
}
}
@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
方法時,消息接收者會收到消息并輸出到控制臺。