引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
创建队列,交换机,并绑定关系
@Configuration
public class RabbitMQSMSConfig {
public static final String SMS_EXCHANGE="sms-exchange";
public static final String SMS_QUEUE="sms-queue";
@Bean(SMS_EXCHANGE)
public Exchange exchange(){
return ExchangeBuilder.topicExchange(SMS_EXCHANGE).durable(true).build();
}
@Bean(SMS_QUEUE)
public Queue queue(){
// return new Queue(SMS_QUEUE);
return QueueBuilder.durable(SMS_QUEUE).build();
}
@Bean
public Binding smsBinding(@Qualifier(SMS_EXCHANGE) Exchange exchange, @Qualifier(SMS_QUEUE)Queue queue){
return BindingBuilder.bind(queue).to(exchange).with("imooc.sms.#").noargs();
}
}
发送消息
rabbitTemplate.convertAndSend(RabbitMQSMSConfig.SMS_EXCHANGE,
"imooc.sms.send.login", GsonUtils.object2String(mqcontext));
监听消息
@Component
public class RabbitMQSMSConsumer {
@RabbitListener(queues = {RabbitMQSMSConfig.SMS_QUEUE})
public void watchQueue(String pyload, Message message){
// pyload就是发送的信息内容
// 获取routingkey
String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
SMSContentQO smsContentQO = GsonUtils.stringToBean(pyload, SMSContentQO.class);
}
}
死信队列的实现
@Bean("queueB")
public Queue queueB(){
Map<String, Object> arguments = new HashMap<>();
//设置死信交换机
arguments.put("x-dead-letter-exchange",Y_DEAD_LETTER_XCHANGE);
//设置死信RoutingKey
arguments.put("x-dead-letter-routing-key","YD");
//设置ttl
arguments.put("x-message-ttl",40000);
return QueueBuilder.durable(QUEUE_B).withArguments(arguments).build();
}