Fanout 就是我们熟悉的广播模式或者订阅模式,给Fanout交换机发送消息,绑定了这个交换机的所有队列都收到这个消息。
生产者工程:
package com.example.demo.rabbitMq.exchange.fanout; 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 FanoutRabbitConfig { @Bean
public Queue AMessage() {
return new Queue("fanout.A");
} @Bean
public Queue BMessage() {
return new Queue("fanout.B");
} @Bean
public Queue CMessage() {
return new Queue("fanout.C");
} @Bean
FanoutExchange fanoutExchange() {
return new FanoutExchange("fanoutExchange");
} @Bean
Binding bindingExchangeA(Queue AMessage, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(AMessage).to(fanoutExchange);
} @Bean
Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(BMessage).to(fanoutExchange);
} @Bean
Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(CMessage).to(fanoutExchange);
} }
发送消息:
package com.example.demo.rabbitMq.exchange.fanout; import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; @Component
public class FanoutSender {
@Autowired
private AmqpTemplate rabbitTemplate; public void send() {
String context = "hi, fanout msg ";
System.out.println("Sender : " + context); //这里使用了A、B、C三个队列绑定到Fanout交换机上面,发送端的routing_key写任何字符都会被忽略
this.rabbitTemplate.convertAndSend("fanoutExchange","XCC", context);
}
}
消费者工程:
package com.example.demo.rabbitMq.exchange.fanout; import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component; @Component
public class FanoutReceiver { @RabbitHandler
@RabbitListener(queues = "fanout.A")
public void processA(String context) {
System.out.println("Receiver A : " + context);
} @RabbitHandler
@RabbitListener(queues = "fanout.B")
public void processB(String context) {
System.out.println("Receiver B : " + context);
} @RabbitHandler
@RabbitListener(queues = "fanout.C")
public void processC(String context) {
System.out.println("Receiver C : " + context);
}
}
测试:
启动消费工程,生产者工程发送消息:
package com.example.demo.rabbitMq; import com.example.demo.rabbitMq.exchange.fanout.FanoutSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitMqFanoutTest {
@Autowired
private FanoutSender fanoutSender; @Test
public void send() throws Exception {
fanoutSender.send();
}
}
结果: