赞
踩
在Spring Boot中嵌入RabbitMQ可以通过添加相应的依赖来完成。首先需要在pom.xml文件中引入spring-boot-starter-amqp依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
然后,在application.properties或者application.yml配置文件中设置RabbitMQ连接信息:
spring.rabbitmq.host=your_rabbitmq_hostname
spring.rabbitmq.port=5672
spring.rabbitmq.username=your_rabbitmq_username
spring.rabbitmq.password=your_rabbitmq_password
最后,创建消息发送者(Producer)和消息接收者(Consumer)类,并使用@Autowired注解将其自动装载到Spring容器中。示例如下:
创建消息发送者类:
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
@Component
public class MessageSender {
@Autowired
private ApplicationContext context;
public void send(String message) {
Queue queue = (Queue) context.getBean("myQueue"); // 获取队列对象
MessageChannel channel = context.getBean(queue.getName(), MessageChannel.class); // 根据队列名称获取消息通道
channel.send(MessageBuilder.withPayload(message).build()); // 发送消息
}
}
创建消息接收者类:
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class MessageReceiver {
@RabbitListener(queues = "myQueue") // 指定监听的队列名称
public void receive(String message) {
System.out.println("Received message: " + message);
}
}
当调用MessageSender
的send()
方法时,会向"myQueue"队列发送消息;
而MessageReceiver
则会监听该队列,并处理接收到的消息。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。