文章目录
SpringBoot整合RabbitMQ
由于我们做项目基于Springboot开发,因此我们这里主要进行Springboot配置开发

YML配置
server:
port: 8081
spring:
rabbitmq:
username: sakura
password: 123456
virtual-host: /
host: 192.168.117.129
port: 5672
Config配置类
我们需要一个配置类,声明我们的交换机和队列,需要注册进容器里面
- 1.声明一个注册交换机FanoutExchange交换机
- 2.声明一个队列EmailQueue
- 3.进行队列和交换机进行
@Configuration
public class RabbitMqConfiguration {
//1. 声明注册fanout模式的交换机
@Bean
public FanoutExchange fanoutExchange() {
return new FanoutExchange("fanout-order-exchange", true, false);
}
//2. 声明队列duanxinqueue smsqueue emailqueue
@Bean
public Queue emailQueue() {
return new Queue("email.fanout.queue", true);
}
@Bean
public Queue smsQueue() {
return new Queue("sms.fanout.queue", true);
}
@Bean
public Queue weixinQueue() {
return new Queue("weixin.fanout.queue", true);
}
//3. 绑定关系
@Bean
public Binding emailBinding() {
return BindingBuilder.bind(emailQueue()).to(fanoutExchange());
}
@Bean
public Binding smsBinding() {
return BindingBuilder.bind(smsQueue()).to(fanoutExchange());
}
@Bean
public Binding weixinBinding() {
return BindingBuilder.bind(weixinQueue()).to(fanoutExchange());
}
}
上述的队列名,交换机名,我们可以定义一个类,声明为常量或者就在RabbitMQ里面创建的exchange或者queue
2.service类
@Service
public class OrderService {
@Autowired
private RabbitTemplate rabbitTemplate;
public void makeOrder(String userId, String productId, int num) {
String orderId = UUID.randomUUID().toString();
System.out.println("订单创建成功:" + orderId);
String exchangeName = "fanout-order-exchange";
String routingKey = "";
/*
* @params1 交换机
* @params2 routingKey/队列名称
* @params3 消息内容
* */
rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId);
}
}
3.测试类
@SpringBootTest
class SpringbootOrderRabbitmqProducerApplicationTests {
@Autowired
private OrderService orderService;
@Test
void contextLoads() throws InterruptedException{
orderService.makeOrder("1","1",12);
}
}
二、进行消费者接受信息
2.1yml文件
server:
port: 8082
spring:
rabbitmq:
username: sakura
password: 123456
virtual-host: /
host: 192.168.117.129
port: 5672
2.2 配置类
@Configuration
public class DirectRabbitMqConfiguration {
//1. 声明注册fanout模式的交换机
@Bean
public DirectExchange directExchange() {
return new DirectExchange("direct-order-exchange", true, false);
}
//2. 声明队列
@Bean
public Queue emailQueueDirect() {
return new Queue("email.direct.queue", true);
}
@Bean
public Queue smsQueueDirect() {
return new Queue("sms.direct.queue", true);
}
@Bean
public Queue we

本文介绍了如何在SpringBoot应用中整合RabbitMQ,包括YML配置、Fanout和Direct模式的交换机与队列声明、服务类实现以及测试用例。在Fanout模式中,消息会被广播到所有绑定的队列;在Direct模式下,消息根据routingKey路由到特定队列。此外,还展示了如何在ES中使用MQ进行消息查询转发。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



