SpringBoot整合RabbitMQ -fanout模式
Posted MyAzhe0ci3
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合RabbitMQ -fanout模式相关的知识,希望对你有一定的参考价值。
SpringBoot整合RabbitMQ -fanout模式
由于是使用真实的阿里云服务器所以需要配置一下rabbitMQ的服务配置yml
注:一定要在阿里云的安全组中开放5672端口
# 服务端口
server:
port: 8080
# 配置rabbitmq服务
spring:
rabbitmq:
username: admin
password: admin
virtual-host: /
host: 139.196.122.115
port: 5672
模拟用户下单
package com.newer.rabbitmq.springbootorderrabbitmqproducer.service;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Service
public class OrderService
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* @deprecated :模拟用户下单
* @param :[userid,productid,num]
* @return: void
*/
public void makeOrder(String userid,String productId,Integer num)
//1.根据商品id查询库存是否充足
//2.保存订单
String orderId= UUID.randomUUID().toString();
System.out.println("订单生成成功:"+orderId);
//3.通过MQ来完成消息的分发
//参数1:交换机 参数2:路由key/queue队列名称 参数3:消息内容
String exchangeName="fanout_order_exchange";
//由于是fanout模式所以不需要路由key
String routingkey="";
rabbitTemplate.convertAndSend(exchangeName,routingkey,orderId);
配置类
package com.newer.rabbitmq.springbootorderrabbitmqproducer.config;
import com.rabbitmq.client.AMQP;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMqConfiguration
//1.声明注册fanout模式的交换机
@Bean
public FanoutExchange fanoutExchange()
return new FanoutExchange("fanout_order_exchange",true,false);
//2.声明队列sms.fanout.queue email.fanout.queue,duanxin.fanout.queue
@Bean
public Queue smsQueue()
return new Queue("sms.fanout.queue");
@Bean
public Queue emailQueue()
return new Queue("email.fanout.queue");
@Bean
public Queue duanxinQueue()
return new Queue("duanxin.fanout.queue");
//3.完成绑定关系(完成交换机与队列之间的绑定关系)
@Bean
public Binding smsBinding()
return BindingBuilder.bind(smsQueue()).to(fanoutExchange());
@Bean
public Binding emailBinding()
return BindingBuilder.bind(emailQueue()).to(fanoutExchange());
@Bean
public Binding duanxinBinding()
return BindingBuilder.bind(duanxinQueue()).to(fanoutExchange());
测试
package com.newer.rabbitmq.springbootorderrabbitmqproducer;
import com.newer.rabbitmq.springbootorderrabbitmqproducer.service.OrderService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootOrderRabbitmqProducerApplicationTests
@Autowired
private OrderService orderService;
@Test
void contextLoads()
orderService.makeOrder("1","1",12);
然后我们看一下他们之间的绑定关系绑定上没
小结:通过springboot整合Rabbitmq是非常便捷的
以上是关于SpringBoot整合RabbitMQ -fanout模式的主要内容,如果未能解决你的问题,请参考以下文章