实体类User
用于进行测试,不一定要用数据库,咱们直接就new出一个对象来就行之后
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
}
测试类
在这里由于我们要对三种方式进行测试,因此测试类中的交换机和队列名称要随之变化,那么对于第一种api方式,我们就使用fanout_exchange交换机和fanout_queue_email和fanout_queue_sms来进行api方式。
@SpringBootTest
class Springboot0118ApplicationTests {
@Autowired
private AmqpAdmin amqpAdmin;
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
amqpAdmin.declareExchange(new FanoutExchange("fanout_exchange"));
amqpAdmin.declareQueue(new Queue("fanout_queue_email"));
amqpAdmin.declareQueue(new Queue("fanout_queue_sms"));
amqpAdmin.declareBinding(new Binding("fanout_queue_email",Binding.DestinationType.QUEUE,"fanout_exchange","",null));
amqpAdmin.declareBinding(new Binding("fanout_queue_sms",Binding.DestinationType.QUEUE,"fanout_exchange","",null));
}
@Test
void publisher(){
User user=new User();
user.setId(10086);
user.setUsername("我爱你俊伟");
rabbitTemplate.convertAndSend("fanout_exchange","",user);
}
}
api方式
先启动主启动类,再启动测试类中publiser()
service
@RabbitListener(queues = "fanout_queue_email")
public void psubConsumerEmail(Message message){
byte[] body = message.getBody();
String s=new String(body);
System.out.println("api方式邮箱业务接收到消息: "+s);
}
@RabbitListener(queues = "fanout_queue_sms")
public void psubConsumerSms(Message message){
byte[] body = message.getBody();
String s=new String(body);
System.out.println("api方式短信业务接收到消息: "+s);
}
配置方式
config
@Bean
public Exchange fanout_exchange(){
return ExchangeBuilder.fanoutExchange("fanout_exchange2").build();
}
// 2、定义两个不同名称的消息队列
@Bean
public Queue fanout_queue_email(){
return new Queue("fanout_queue_email2");
}
@Bean
public Queue fanout_queue_sms(){
return new Queue("fanout_queue_sms2");
}
// 3、将两个不同名称的消息队列与交换器进行绑定
@Bean
public Binding bindingEmail2(){
return BindingBuilder.bind(fanout_queue_email()).to(fanout_exchange()).with("").noargs();
}
@Bean
public Binding bindingSms2(){
return BindingBuilder.bind(fanout_queue_sms()).to(fanout_exchange()).with("").noargs();
}
其实对于配置方式而言,除了配置和api方式不同外,其他进行测试的步骤都是一样的
注解方式
service
@RabbitListener(bindings =@QueueBinding(value =@Queue("fanout_queue_email3"), exchange =@Exchange(value = "fanout_exchange3",type = "fanout")))
public void psubConsumerEmailAno(User user) {
System.out.println("注解方式邮件业务接收到消息: "+user);
}
@RabbitListener(bindings =@QueueBinding(value =@Queue("fanout_queue_sms3"),exchange =@Exchange(value = "fanout_exchange3",type = "fanout")))
public void psubConsumerSmsAno(User user) {
System.out.println("注解方式短信业务接收到消息: "+user);
}
没错对于注解方式而言,除了service和api方式不同外,其他进行测试的步骤都是一样的
笔者写不下去了,肚子疼要上厕所了。。。