1. Fanout模式和Direct模式对比
? Fanout模式是由Fanout交换机向所有绑定的队列发送消息, 而Direct模式是向指定目标的队列进行消息发送, 前者是广播, 后者是匹配推送 .
参考>>
fanout:
direct:
2. 编码实现Direct模式
工程延续上一章>>
2.1 在生产者中定义交换机和队列并进行绑定
@Configuration
public class RabbitMQConfiguration {
public static final String exchangeName = "login_direct_exchange";
@Bean
public DirectExchange fanoutExchange() {
return new DirectExchange(exchangeName,true,false);
}
@Bean
public Queue smsQueue() {
return new Queue("sms.direct.queue");
}
@Bean
public Queue mailQueue() {
return new Queue("mail.direct.queue");
}
@Bean
public Binding smsBinding() {
return BindingBuilder.bind(smsQueue()).to(fanoutExchange()).
with("sms");
}
@Bean
public Binding mailBinding() {
return BindingBuilder.bind(mailQueue()).to(fanoutExchange()).
with("mail");
}
}
2.2 登录逻辑案例–消息的生产
@Service
public class LoginService {
@Resource
private RabbitTemplate rabbitTemplate;
public void register(String phone, String userInfo) {
System.out.println(phone + " 用户已入库 " + userInfo);
String routingKey = "mail";
rabbitTemplate.convertAndSend(RabbitMQConfiguration.exchangeName, routingKey, userInfo);
String routingKey2 = "sms";
rabbitTemplate.convertAndSend(RabbitMQConfiguration.exchangeName, routingKey2, userInfo);
}
}
测试代码:
@SpringBootTest
class ProducerServerApplicationTests {
@Resource
private LoginService loginService;
@Test
void contextLoads() {
loginService.register("119", "这是用户信息");
}
}
执行测试用例模拟用户注册并将消息投递到相应的队列中
2.3 在消费者中编写短信服务和邮件服务完成队列中消息的消费
短信服务
@Service
@RabbitListener(queues = {"sms.direct.queue"})
public class SMSService {
@RabbitHandler
public void sandSMS(String message) {
System.out.println("向 "+message+" 发送了短信");
}
}
邮件服务
@Service
@RabbitListener(queues = {"mail.direct.queue"})
public class MailService {
@RabbitHandler
public void sandMail(String message) {
System.out.println("向 "+message+" 发送了邮件");
}
}
启动消费者工程, 查看队列中的消息被消费
3. 完整项目代码
码云仓库>>
|