RabbitMQ---SpringBoot整合RabbitMQ(Fanout交换器)

旧街凉风 提交于 2020-03-01 10:12:54

Fanout交换器特点:

      各个队列与Topic交换器之间没有路由键绑定配置,发送者发送一条消息给交换器,只要与此交换器绑定的队列,都会接收到消息。

 

 

生产者module,只需要指定交换器,发送消息也只需要指定交换器即可

         pom.xml导入RabbitMQ坐标

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

          application.properties配置RabbitMQ信息

#RabbitMQ基本信息
spring.rabbitmq.host=182.61.40.184
spring.rabbitmq.port=5672
spring.rabbitmq.username=rabbitmq
spring.rabbitmq.password=rabbitmq

#自定义配置
#设置交换器名称   
spring.rabbitmq.exchange.name=fanoutExchange

          创建Controller,通过浏览器请求,发送消息到RabbitMQ

@Controller
public class RabbitMQController {
	
	@Autowired
	private AmqpTemplate amqpTemplate;
	
	@Value("${spring.rabbitmq.exchange.name}")
	String exchange;
	
	
	@RequestMapping(value="/fanoutExchangeTest",method=RequestMethod.GET)
	@ResponseBody
	public void fanoutExchangeTest() throws InterruptedException {
		while (true) {
			Thread.sleep(1000);
			amqpTemplate.convertAndSend(exchange, "", "fanoutExchange....");
		}
	}
	
}

 

创建消息消费者module:编写队列消息处理组件,配置队列名称,交换器名称和类型,并进行绑定。

        pom.xml导入RabbitMQ坐标

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

        application.properties配置RabbitMQ信息

#RabbitMQ基本信息
spring.rabbitmq.host=182.61.40.184
spring.rabbitmq.port=5672
spring.rabbitmq.username=rabbitmq
spring.rabbitmq.password=rabbitmq

#自定义信息
#设置交换器名称
spring.rabbitmq.exchageName=fanoutExchange
#设置队列A名称
spring.rabbitmq.queueA=fanoutQueueA
#设置队列B名称
spring.rabbitmq.queueB=fanoutQueueB

         队列A处理消息组件

@Component
@RabbitListener(
	bindings = @QueueBinding(
		value = @Queue(value = "${spring.rabbitmq.queueA}",autoDelete = "true"),
		exchange = @Exchange(value="${spring.rabbitmq.exchageName}",type = ExchangeTypes.FANOUT)
	)
)
public class RabbitMQComponentA {
	
	@RabbitHandler
	public void getMessage(String msg) {
		System.out.println("队列fanoutQueueA收到消息:" + msg + ".........");
	}
	
}

       队列B处理消息组件

@Component
@RabbitListener(
	bindings = @QueueBinding(
		value = @Queue(value = "${spring.rabbitmq.queueB}",autoDelete = "true"),
		exchange = @Exchange(value="${spring.rabbitmq.exchageName}",type = ExchangeTypes.FANOUT)
	)
)
public class RabbitMQComponentB {
	
	@RabbitHandler
	public void getMessage(String msg) {
		System.out.println("队列fanoutQueueB收到消息:" + msg + ".........");
	}
	
}

 

测试:

       启动两个module,访问Controller

 

 

 

 

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!