发送端服务器
注册队列 -- 配置文件实现
@Configuration
public class RabbitConfig {
//注册队列
@Bean
public Queue Queue(){
return new Queue("hello");
}
}
消息发送
@Component
public class MessageSender{
@Autowired
AmqpTemplate amqpTemplate;
public void send() {
String content = "hello " + new Date();
System.out.println("Sender-message : " + content);
this.amqpTemplate.convertAndSend("hello", content);
}
}
接收端服务器
实现方式一
@Component
@RabbitListener(queues = "hello")
public class MessageReceiver {
@RabbitHandler
public void process(@Payload String foo) {
System.out.println(foo);
}
}
实现方式二:
@Component
public class MessageReceiver {
@RabbitListener(queues = "hello")
public void process(String content){
System.out.println("Receiver Value : " + content);
}
}
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = WebClientCoreApplication.class)
@WebAppConfiguration
public class RabbitTest {
@Autowired
MessageSender messageSender;
@Test
public void testRabbit(){
messageSender.send();
}
}
//WebClientCoreApplication 为当前服务的启动类
测试过程
- 启动接收服务器
- 执行测试类
期望值
- 发送服务器正常打印
- 接收服务器正常打印
- RabbitMQ 管理端可以正常查阅发送记录