整合方法详见:
整合好之后,打开 http://localhost:15672,开启rabbitMq。
使用方法:
1.定义一个Config类,用于定义Queue和Exchanger,然后将这2个类绑定起来,用于发送文件。
@Configuration
public class FanoutRabbitConfig {
/**
* 1.定义一个Queue,然后定义一个Exchange,绑定Queue和Exchange,即可实现发送、接收
* 2.接收类需要定义一个Listener,用于监听发送的相应消息
* @return
*/
@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);
}
}
2.定义Sender类,用于编辑报文内容,并使用AmqpTemplate的convertAndSend方法发送报文。值得注意的是:convertAndSend(“fanoutExchange”,"", context)方法中,fanoutExchange要和FanoutRabbitConfig中定义的FanoutExchange名称完全一致。
@Component
public class FanoutSender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String context = "hi, fanout msg ";
System.out.println("Sender : " + context);
this.rabbitTemplate.convertAndSend("fanoutExchange","", context);
}
}
3.定义Receiver类,用与根据注册在Config中的报文名称接收报文内容。这里需要定义Listener,@RabbitListener(queues = “fanout.A”),其中,fanout.A要在Config类中定义。
@Component
@RabbitListener(queues = "fanout.A")
public class FanoutReceiverA {
@RabbitHandler
public void process(String message) {
System.out.println("fanout Receiver A : " + message);
}
}
4.编写test类。
@RunWith(SpringRunner.class)
@SpringBootTest
public class FanoutTest {
@Autowired
private FanoutSender sender;
@Test
public void fanoutSender() throws Exception {
sender.send();
}
}
控制台打印如下:
Sender : hi, fanout msg
2018-11-19 11:03:28.355 INFO 5528 --- [ Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@37883b97: startup date [Mon Nov 19 11:03:24 CST 2018]; root of context hierarchy
2018-11-19 11:03:28.355 INFO 5528 --- [ Thread-3] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 2147483647
2018-11-19 11:03:28.385 INFO 5528 --- [ Thread-3] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
fanout Receiver C: hi, fanout msg
fanout Receiver A : hi, fanout msg
fanout Receiver B: hi, fanout msg