RabbitMQ快速使用代碼手冊
本篇博客的內容為RabbitMQ在開發過程中的快速上手使用,側重于代碼部分,幾乎沒有相關概念的介紹,相關概念請參考以下csdn博客,兩篇都是我找的精華帖,供大家學習。本篇博客也持續更新~~~內容代碼部分由于word轉md格式有些問題,可以直接查看我的有道云筆記,鏈接:https://note.youdao.com/s/Ab7Cjiu
參考文檔csdn博客:
(相關資料圖)
基礎部分:https://blog.csdn.net/qq_35387940/article/details/100514134
高級部分:https://blog.csdn.net/weixin_49076273/article/details/124991012
application.ymlserver:port: 8021spring:#給項目來個名字application:name: rabbitmq-provider#配置rabbitMq 服務器rabbitmq:host: 127.0.0.1port: 5672username: rootpassword: root#虛擬host 可以不設置,使用server默認hostvirtual-host: JCcccHost#確認消息已發送到交換機(Exchange)#publisher-confirms: truepublisher-confirm-type: correlated#確認消息已發送到隊列(Queue)publisher-returns: true完善更多信息
spring:rabbitmq:host: localhostport: 5672virtual-host: /username: guestpassword: guestpublisher-confirm-type: correlatedpublisher-returns: truetemplate:mandatory: trueretry:#發布重試,默認falseenabled: true#重試時間 默認1000msinitial-interval: 1000#重試最大次數 最大3max-attempts: 3#重試最大間隔時間max-interval: 10000#重試的時間隔乘數,比如配2,0第一次等于10s,第二次等于20s,第三次等于40smultiplier: 1listener:\# 默認配置是simpletype: simplesimple:\# 手動ack Acknowledge mode of container. auto noneacknowledge-mode: manual#消費者調用程序線程的最小數量concurrency: 10#消費者最大數量max-concurrency: 10#限制消費者每次只處理一條信息,處理完在繼續下一條prefetch: 1#啟動時是否默認啟動容器auto-startup: true#被拒絕時重新進入隊列default-requeue-rejected: true相關注解說明@RabbitListener 注解是指定某方法作為消息消費的方法,例如監聽某 Queue里面的消息。
@RabbitListener標注在方法上,直接監聽指定的隊列,此時接收的參數需要與發送市類型一致。
\@Componentpublic class PointConsumer {//監聽的隊列名\@RabbitListener(queues = \"point.to.point\")public void processOne(String name) {System.out.println(\"point.to.point:\" + name);}}@RabbitListener 可以標注在類上面,需配合 @RabbitHandler 注解一起使用
@RabbitListener 標注在類上面表示當有收到消息的時候,就交給@RabbitHandler 的方法處理,根據接受的參數類型進入具體的方法中。
\@Component\@RabbitListener(queues = \"consumer_queue\")public class Receiver {\@RabbitHandlerpublic void processMessage1(String message) {System.out.println(message);}\@RabbitHandlerpublic void processMessage2(byte\[\] message) {System.out.println(new String(message));}}@Payload
可以獲取消息中的 body 信息
\@RabbitListener(queues = \"debug\")public void processMessage1(@Payload String body) {System.out.println(\"body:\"+body);}@Header,@Headers
可以獲得消息中的 headers 信息
\@RabbitListener(queues = \"debug\")public void processMessage1(@Payload String body, \@Header String token){System.out.println(\"body:\"+body);System.out.println(\"token:\"+token);}\@RabbitListener(queues = \"debug\")public void processMessage1(@Payload String body, \@HeadersMap\ headers) {System.out.println(\"body:\"+body);System.out.println(\"Headers:\"+headers);} 快速使用配置xml文件\org.springframework.boot\ \spring-boot-starter-amqp\ \ 配置exchange、queue注解快速創建版本\@Configurationpublic class RabbitmqConfig {//創建交換機//通過ExchangeBuilder能創建direct、topic、Fanout類型的交換機\@Bean(\"bootExchange\")public Exchange bootExchange() {returnExchangeBuilder.topicExchange(\"zx_topic_exchange\").durable(true).build();}//創建隊列\@Bean(\"bootQueue\")public Queue bootQueue() {return QueueBuilder.durable(\"zx_queue\").build();}/\*\*\* 將隊列與交換機綁定\*\* \@param queue\* \@param exchange\* \@return\*/\@Beanpublic Binding bindQueueExchange(@Qualifier(\"bootQueue\") Queue queue,\@Qualifier(\"bootExchange\") Exchange exchange) {returnBindingBuilder.bind(queue).to(exchange).with(\"boot.#\").noargs();}}Directimport org.springframework.amqp.core.Binding;import org.springframework.amqp.core.BindingBuilder;import org.springframework.amqp.core.DirectExchange;import org.springframework.amqp.core.Queue;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/\*\*\* \@Author : JCccc\* \@CreateTime : 2019/9/3\* \@Description :\*\*/\@Configurationpublic class DirectRabbitConfig {//隊列 起名:TestDirectQueue\@Beanpublic Queue TestDirectQueue() {//durable:是否持久化,默認是false,持久化隊列:會被存儲在磁盤上,當消息代理重啟時仍然存在,暫存隊列:當前連接有效//exclusive:默認也是false,只能被當前創建的連接使用,而且當連接關閉后隊列即被刪除。此參考優先級高于durable//autoDelete:是否自動刪除,當沒有生產者或者消費者使用此隊列,該隊列會自動刪除。// return new Queue(\"TestDirectQueue\",true,true,false);//一般設置一下隊列的持久化就好,其余兩個就是默認falsereturn new Queue(\"TestDirectQueue\",true);}//Direct交換機 起名:TestDirectExchange\@BeanDirectExchange TestDirectExchange() {// return new DirectExchange(\"TestDirectExchange\",true,true);return new DirectExchange(\"TestDirectExchange\",true,false);}//綁定 將隊列和交換機綁定, 并設置用于匹配鍵:TestDirectRouting\@BeanBinding bindingDirect() {returnBindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with(\"TestDirectRouting\");}\@BeanDirectExchange lonelyDirectExchange() {return new DirectExchange(\"lonelyDirectExchange\");}}Fanoutimport org.springframework.amqp.core.Binding;import org.springframework.amqp.core.BindingBuilder;import org.springframework.amqp.core.FanoutExchange;import org.springframework.amqp.core.Queue;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/\*\*\* \@Author : JCccc\* \@CreateTime : 2019/9/3\* \@Description :\*\*/\@Configurationpublic class FanoutRabbitConfig {/\*\*\* 創建三個隊列 :fanout.A fanout.B fanout.C\* 將三個隊列都綁定在交換機 fanoutExchange 上\* 因為是扇型交換機, 路由鍵無需配置,配置也不起作用\*/\@Beanpublic Queue queueA() {return new Queue(\"fanout.A\");}\@Beanpublic Queue queueB() {return new Queue(\"fanout.B\");}\@Beanpublic Queue queueC() {return new Queue(\"fanout.C\");}\@BeanFanoutExchange fanoutExchange() {return new FanoutExchange(\"fanoutExchange\");}\@BeanBinding bindingExchangeA() {return BindingBuilder.bind(queueA()).to(fanoutExchange());}\@BeanBinding bindingExchangeB() {return BindingBuilder.bind(queueB()).to(fanoutExchange());}\@BeanBinding bindingExchangeC() {return BindingBuilder.bind(queueC()).to(fanoutExchange());}}Topicimport org.springframework.amqp.core.Binding;import org.springframework.amqp.core.BindingBuilder;import org.springframework.amqp.core.Queue;import org.springframework.amqp.core.TopicExchange;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/\*\*\* \@Author : JCccc\* \@CreateTime : 2019/9/3\* \@Description :\*\*/\@Configurationpublic class TopicRabbitConfig {//綁定鍵public final static String man = \"topic.man\";public final static String woman = \"topic.woman\";\@Beanpublic Queue firstQueue() {return new Queue(TopicRabbitConfig.man);}\@Beanpublic Queue secondQueue() {return new Queue(TopicRabbitConfig.woman);}\@BeanTopicExchange exchange() {return new TopicExchange(\"topicExchange\");}//將firstQueue和topicExchange綁定,而且綁定的鍵值為topic.man//這樣只要是消息攜帶的路由鍵是topic.man,才會分發到該隊列\@BeanBinding bindingExchangeMessage() {return BindingBuilder.bind(firstQueue()).to(exchange()).with(man);}//將secondQueue和topicExchange綁定,而且綁定的鍵值為用上通配路由鍵規則topic.#// 這樣只要是消息攜帶的路由鍵是以topic.開頭,都會分發到該隊列\@BeanBinding bindingExchangeMessage2() {returnBindingBuilder.bind(secondQueue()).to(exchange()).with(\"topic.#\");}}生產者發送消息直接發送給隊列
//指定消息隊列的名字,直接發送消息到消息隊列中\@Testpublic void testSimpleQueue() {// 隊列名稱String queueName = \"simple.queue\";// 消息String message = \"hello, spring amqp!\";// 發送消息rabbitTemplate.convertAndSend(queueName, message);}發送給交換機,然后走不同的模式
////指定交換機的名字,將消息發送給交換機,然后不同模式下,消息隊列根據key得到消息\@Testpublic void testSendDirectExchange() {// 交換機名稱,有三種類型String exchangeName = \"itcast.direct\";// 消息String message =\"紅色警報!日本亂排核廢水,導致海洋生物變異,驚現哥斯拉!\";// 發送消息,red為隊列的key,因此此隊列會得到消息rabbitTemplate.convertAndSend(exchangeName, \"red\", message);}也可以將發送的消息封裝到HashMap中然后發送給交換機
import org.springframework.amqp.rabbit.core.RabbitTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.HashMap;import java.util.Map;import java.util.UUID;/\*\*\* \@Author : JCccc\* \@CreateTime : 2019/9/3\* \@Description :\*\*/\@RestControllerpublic class SendMessageController {\@AutowiredRabbitTemplate rabbitTemplate;//使用RabbitTemplate,這提供了接收/發送等等方法\@GetMapping(\"/sendDirectMessage\")public String sendDirectMessage() {String messageId = String.valueOf(UUID.randomUUID());String messageData = \"test message, hello!\";String createTime =LocalDateTime.now().format(DateTimeFormatter.ofPattern(\"yyyy-MM-ddHH:mm:ss\"));Map\ map=new HashMap\<\>();map.put(\"messageId\",messageId);map.put(\"messageData\",messageData);map.put(\"createTime\",createTime);//將消息攜帶綁定鍵值:TestDirectRouting 發送到交換機TestDirectExchangerabbitTemplate.convertAndSend(\"TestDirectExchange\",\"TestDirectRouting\", map);return \"ok\";}} 消費者接收消息//使用注解@RabbitListener定義當前方法監聽RabbitMQ中指定名稱的消息隊列。\@Componentpublic class MessageListener {\@RabbitListener(queues = \"direct_queue\")public void receive(String id){System.out.println(\"已完成短信發送業務(rabbitmq direct),id:\"+id);}}參數用Map接收也可以\@Component\@RabbitListener(queues = \"TestDirectQueue\")//監聽的隊列名稱TestDirectQueuepublic class DirectReceiver {\@RabbitHandlerpublic void process(Map testMessage) {System.out.println(\"DirectReceiver消費者收到消息 : \" +testMessage.toString());}}高級特性消息可靠性傳遞有confirm和return兩種
在application.yml中添加以下配置項:
server:port: 8021spring:#給項目來個名字application:name: rabbitmq-provider#配置rabbitMq 服務器rabbitmq:host: 127.0.0.1port: 5672username: rootpassword: root#虛擬host 可以不設置,使用server默認hostvirtual-host: JCcccHost#確認消息已發送到交換機(Exchange)#publisher-confirms: truepublisher-confirm-type: correlated#確認消息已發送到隊列(Queue)publisher-returns: true有兩種配置方法:
寫到配置類中
寫到工具類或者普通類中,但是這個類得實現那兩個接口
寫法一編寫消息確認回調函數
import org.springframework.amqp.core.Message;import org.springframework.amqp.rabbit.connection.ConnectionFactory;import org.springframework.amqp.rabbit.connection.CorrelationData;import org.springframework.amqp.rabbit.core.RabbitTemplate;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;\@Configurationpublic class RabbitConfig {\@Beanpublic RabbitTemplate createRabbitTemplate(ConnectionFactoryconnectionFactory){RabbitTemplate rabbitTemplate = new RabbitTemplate();rabbitTemplate.setConnectionFactory(connectionFactory);//設置開啟Mandatory,才能觸發回調函數,無論消息推送結果怎么樣都強制調用回調函數rabbitTemplate.setMandatory(true);rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {\@Overridepublic void confirm(CorrelationData correlationData, boolean ack, Stringcause) {System.out.println(\"ConfirmCallback:\"+\"相關數據:\"+correlationData);System.out.println(\"ConfirmCallback: \"+\"確認情況:\"+ack);System.out.println(\"ConfirmCallback: \"+\"原因:\"+cause);}});rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {\@Overridepublic void returnedMessage(Message message, int replyCode, StringreplyText, String exchange, String routingKey) {System.out.println(\"ReturnCallback: \"+\"消息:\"+message);System.out.println(\"ReturnCallback: \"+\"回應碼:\"+replyCode);System.out.println(\"ReturnCallback: \"+\"回應信息:\"+replyText);System.out.println(\"ReturnCallback: \"+\"交換機:\"+exchange);System.out.println(\"ReturnCallback: \"+\"路由鍵:\"+routingKey);}});return rabbitTemplate;}}寫法二\@Component\@Slf4jpublic class SmsRabbitMqUtils implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {\@Resourceprivate RedisTemplate\ redisTemplate;\@Resourceprivate RabbitTemplate rabbitTemplate;private String finalId = null;private SmsDTO smsDTO = null;/\*\*\* 發布者確認的回調\*\* \@param correlationData 回調的相關數據。\* \@param b ack為真,nack為假\* \@param s 一個可選的原因,用于nack,如果可用,否則為空。\*/\@Overridepublic void confirm(CorrelationData correlationData, boolean b, Strings) {// 消息發送成功,將redis中消息的狀態(status)修改為1if (b) {redisTemplate.opsForHash().put(RedisConstant.SMS_MESSAGE_PREFIX +finalId, \"status\", 1);} else {// 發送失敗,放入redis失敗集合中,并刪除集合數據log.error(\"短信消息投送失敗:{}\--\>{}\", correlationData, s);redisTemplate.delete(RedisConstant.SMS_MESSAGE_PREFIX + finalId);redisTemplate.opsForHash().put(RedisConstant.MQ_PRODUCER, finalId,this.smsDTO);}}/\*\*\* 發生異常時的消息返回提醒\*\* \@param returnedMessage\*/\@Overridepublic void returnedMessage(ReturnedMessage returnedMessage) {log.error(\"發生異常,返回消息回調:{}\", returnedMessage);// 發送失敗,放入redis失敗集合中,并刪除集合數據redisTemplate.delete(RedisConstant.SMS_MESSAGE_PREFIX + finalId);redisTemplate.opsForHash().put(RedisConstant.MQ_PRODUCER, finalId,this.smsDTO);}\@PostConstructpublic void init() {rabbitTemplate.setConfirmCallback(this);rabbitTemplate.setReturnsCallback(this);}} 消息確認機制手動確認
yml配置#手動確認 manuallistener:simple:acknowledge-mode: manual寫法一首先在消費者項目中創建MessageListenerConfig
import com.elegant.rabbitmqconsumer.receiver.MyAckReceiver;import org.springframework.amqp.core.AcknowledgeMode;import org.springframework.amqp.core.Queue;importorg.springframework.amqp.rabbit.connection.CachingConnectionFactory;importorg.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;\@Configurationpublic class MessageListenerConfig {\@Autowiredprivate CachingConnectionFactory connectionFactory;\@Autowiredprivate MyAckReceiver myAckReceiver;//消息接收處理類\@Beanpublic SimpleMessageListenerContainer simpleMessageListenerContainer() {SimpleMessageListenerContainer container = newSimpleMessageListenerContainer(connectionFactory);container.setConcurrentConsumers(1);container.setMaxConcurrentConsumers(1);container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //RabbitMQ默認是自動確認,這里改為手動確認消息//設置一個隊列container.setQueueNames(\"TestDirectQueue\");//如果同時設置多個如下: 前提是隊列都是必須已經創建存在的//container.setQueueNames(\"TestDirectQueue\",\"TestDirectQueue2\",\"TestDirectQueue3\");//另一種設置隊列的方法,如果使用這種情況,那么要設置多個,就使用addQueues//container.setQueues(new Queue(\"TestDirectQueue\",true));//container.addQueues(new Queue(\"TestDirectQueue2\",true));//container.addQueues(new Queue(\"TestDirectQueue3\",true));container.setMessageListener(myAckReceiver);return container;}}然后創建手動確認監聽類MyAckReceiver(手動確認模式需要實現ChannelAwareMessageListener)
import com.rabbitmq.client.Channel;import org.springframework.amqp.core.Message;importorg.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;import org.springframework.stereotype.Component;import java.io.ByteArrayInputStream;import java.io.ObjectInputStream;import java.util.Map;\@Componentpublic class MyAckReceiver implements ChannelAwareMessageListener {\@Overridepublic void onMessage(Message message, Channel channel) throws Exception{long deliveryTag = message.getMessageProperties().getDeliveryTag();try {byte\[\] body = message.getBody();ObjectInputStream ois = new ObjectInputStream(newByteArrayInputStream(body));Map\ msgMap = (Map\) ois.readObject();String messageId = msgMap.get(\"messageId\");String messageData = msgMap.get(\"messageData\");String createTime = msgMap.get(\"createTime\");ois.close();System.out.println(\" MyAckReceiver messageId:\"+messageId+\"messageData:\"+messageData+\" createTime:\"+createTime);System.out.println(\"消費的主題消息來自:\"+message.getMessageProperties().getConsumerQueue());channel.basicAck(deliveryTag, true);//第二個參數,手動確認可以被批處理,當該參數為 true 時,則可以一次性確認delivery_tag 小于等于傳入值的所有消息//channel.basicReject(deliveryTag,true);//第二個參數,true會重新放回隊列,所以需要自己根據業務邏輯判斷什么時候使用拒絕} catch (Exception e) {channel.basicReject(deliveryTag, false);e.printStackTrace();}}} 如果想實現不同的隊列,有不同的監聽確認處理機制,做不同的業務處理,那么這樣做:
首先需要在配置類中綁定隊列,然后只需要根據消息來自不同的隊列名進行區分處理即可
import com.rabbitmq.client.Channel;import org.springframework.amqp.core.Message;importorg.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;import org.springframework.stereotype.Component;import java.io.ByteArrayInputStream;import java.io.ObjectInputStream;import java.util.Map;\@Componentpublic class MyAckReceiver implements ChannelAwareMessageListener {\@Overridepublic void onMessage(Message message, Channel channel) throws Exception{long deliveryTag = message.getMessageProperties().getDeliveryTag();try {byte\[\] body = message.getBody();ObjectInputStream ois = new ObjectInputStream(newByteArrayInputStream(body));Map\ msgMap = (Map\) ois.readObject();String messageId = msgMap.get(\"messageId\");String messageData = msgMap.get(\"messageData\");String createTime = msgMap.get(\"createTime\");ois.close();if(\"TestDirectQueue\".equals(message.getMessageProperties().getConsumerQueue())){System.out.println(\"消費的消息來自的隊列名為:\"+message.getMessageProperties().getConsumerQueue());System.out.println(\"消息成功消費到 messageId:\"+messageId+\"messageData:\"+messageData+\" createTime:\"+createTime);System.out.println(\"執行TestDirectQueue中的消息的業務處理流程\...\...\");}if(\"fanout.A\".equals(message.getMessageProperties().getConsumerQueue())){System.out.println(\"消費的消息來自的隊列名為:\"+message.getMessageProperties().getConsumerQueue());System.out.println(\"消息成功消費到 messageId:\"+messageId+\"messageData:\"+messageData+\" createTime:\"+createTime);System.out.println(\"執行fanout.A中的消息的業務處理流程\...\...\");}channel.basicAck(deliveryTag, true);//channel.basicReject(deliveryTag, true);//為true會重新放回隊列} catch (Exception e) {channel.basicReject(deliveryTag, false);e.printStackTrace();}}} 寫法二\@Component\@Slf4jpublic class SendSmsListener {\@Resourceprivate RedisTemplate\ redisTemplate;\@Resourceprivate SendSmsUtils sendSmsUtils;/\*\*\* 監聽發送短信普通隊列\* \@param smsDTO\* \@param message\* \@param channel\* \@throws IOException\*/\@RabbitListener(queues = SMS_QUEUE_NAME)public void sendSmsListener(SmsDTO smsDTO, Message message, Channelchannel) throws IOException {String messageId = message.getMessageProperties().getMessageId();int retryCount = (int)redisTemplate.opsForHash().get(RedisConstant.SMS_MESSAGE_PREFIX +messageId, \"retryCount\");if (retryCount \> 3) {//重試次數大于3,直接放到死信隊列log.error(\"短信消息重試超過3次:{}\", messageId);//basicReject方法拒絕deliveryTag對應的消息,第二個參數是否requeue,true則重新入隊列,否則丟棄或者進入死信隊列。//該方法reject后,該消費者還是會消費到該條被reject的消息。channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);redisTemplate.delete(RedisConstant.SMS_MESSAGE_PREFIX + messageId);return;}try {String phoneNum = smsDTO.getPhoneNum();String code = smsDTO.getCode();if(StringUtils.isAnyBlank(phoneNum,code)){throw new RuntimeException(\"sendSmsListener參數為空\");}// 發送消息SendSmsResponse sendSmsResponse = sendSmsUtils.sendSmsResponse(phoneNum,code);SendStatus\[\] sendStatusSet = sendSmsResponse.getSendStatusSet();SendStatus sendStatus = sendStatusSet\[0\];if(!\"Ok\".equals(sendStatus.getCode()) \|\|!\"sendsuccess\".equals(sendStatus.getMessage())){throw new RuntimeException(\"發送驗證碼失敗\");}//手動確認消息channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);log.info(\"短信發送成功:{}\",smsDTO);redisTemplate.delete(RedisConstant.SMS_MESSAGE_PREFIX + messageId);} catch (Exception e) {redisTemplate.opsForHash().put(RedisConstant.SMS_MESSAGE_PREFIX+messageId,\"retryCount\",retryCount+1);channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);}}/\*\*\* 監聽到發送短信死信隊列\* \@param sms\* \@param message\* \@param channel\* \@throws IOException\*/\@RabbitListener(queues = SMS_DELAY_QUEUE_NAME)public void smsDelayQueueListener(SmsDTO sms, Message message, Channelchannel) throws IOException {try{log.error(\"監聽到死信隊列消息==\>{}\",sms);channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);}catch (Exception e){channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);}}} 消費端限流#配置RabbitMQspring:rabbitmq:host: 192.168.126.3port: 5672username: guestpassword: guestvirtual-host: /#開啟自動確認 none 手動確認 manuallistener:simple:#消費端限流機制必須開啟手動確認acknowledge-mode: manual#消費端最多拉取的消息條數,簽收后不滿該條數才會繼續拉取prefetch: 5消息存活時間TTL可以設置隊列的存活時間,也可以設置具體消息的存活時間
設置隊列中所有消息的存活時間
return QueueBuilder
.durable(QUEUE_NAME)//隊列持久化
.ttl(10000)//設置隊列的所有消息存活10s
.build();
即在創建隊列時,設置存活時間
設置某條消息的存活時間
//發送消息,并設置該消息的存活時間
\@Testpublic void testSendMessage(){//1.創建消息屬性MessageProperties messageProperties = new MessageProperties();//2.設置存活時間messageProperties.setExpiration(\"10000\");//3.創建消息對象Message message = newMessage(\"sendMessage\...\".getBytes(),messageProperties);//4.發送消息rabbitTemplate.convertAndSend(\"my_topic_exchange1\",\"my_routing\",message);}若設置中間的消息的存活時間,當過期時,該消息不會被移除,但是該消息已經不會被消費了,需要等到該消息到隊里頂端才會被移除。因為隊列是頭出,尾進,故而要移除它需要等到它在頂端時才可以。
在隊列設置存活時間,也在單條消息設置存活時間,則以時間短的為準
死信隊列死信隊列和普通隊列沒有任何區別,只需要將普通隊列需要綁定死信交換機和死信隊列就能夠實現功能
import org.springframework.amqp.core.\*;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;\@Configuration//Rabbit配置類public class RabbitConfig4 {private final String DEAD_EXCHANGE = \"dead_exchange\";private final String DEAD_QUEUE = \"dead_queue\";private final String NORMAL_EXCHANGE = \"normal_exchange\";private final String NORMAL_QUEUE = \"normal_queue\";//創建死信交換機\@Bean(DEAD_EXCHANGE)public Exchange deadExchange(){return ExchangeBuilder.topicExchange(DEAD_EXCHANGE)//交換機類型 ;參數為名字topic為通配符模式的交換機.durable(true)//是否持久化,true即存到磁盤,false只在內存上.build();}//創建死信隊列\@Bean(DEAD_QUEUE)public Queue deadQueue(){return QueueBuilder.durable(DEAD_QUEUE)//隊列持久化//.maxPriority(10)//設置隊列的最大優先級,最大可以設置255,但官網推薦不超過10,太高比較浪費資源.build();}//死信交換機綁定死信隊列\@Bean//@Qualifier注解,使用名稱裝配進行使用public Binding bindDeadQueue(@Qualifier(DEAD_EXCHANGE) Exchangeexchange, \@Qualifier(DEAD_QUEUE) Queue queue){return BindingBuilder.bind(queue).to(exchange).with(\"dead_routing\").noargs();}//創建普通交換機\@Bean(NORMAL_EXCHANGE)public Exchange normalExchange(){return ExchangeBuilder.topicExchange(NORMAL_EXCHANGE)//交換機類型 ;參數為名字topic為通配符模式的交換機.durable(true)//是否持久化,true即存到磁盤,false只在內存上.build();}//創建普通隊列\@Bean(NORMAL_QUEUE)public Queue normalQueue(){return QueueBuilder.durable(NORMAL_QUEUE)//隊列持久化//.maxPriority(10)//設置隊列的最大優先級,最大可以設置255,但官網推薦不超過10,太高比較浪費資源.deadLetterExchange(DEAD_EXCHANGE)//綁定死信交換機.deadLetterRoutingKey(\"dead_routing\")//死信隊列路由關鍵字.ttl(10000)//消息存活10s.maxLength(10)//隊列最大長度為10.build();}//普通交換機綁定普通隊列\@Bean//@Qualifier注解,使用名稱裝配進行使用public Binding bindNormalQueue(@Qualifier(NORMAL_EXCHANGE) Exchangeexchange, \@Qualifier(NORMAL_QUEUE) Queue queue){return BindingBuilder.bind(queue).to(exchange).with(\"my_routing\").noargs();}}延遲隊列RabbitMQ并未實現延遲隊列功能,所以可以通過死信隊列實現延遲隊列的功能
即給普通隊列設置存活時間30分鐘,過期后發送至死信隊列,在死信消費者監聽死信隊列消息,查看訂單狀態,是否支付,未支付則取消訂單,回退庫存即可。
消費者監聽延遲隊列
\@Componentpublic class ExpireOrderConsumer {//監聽過期訂單隊列\@RabbitListener(queues = \"expire_queue\")public void listenMessage(String orderId){//模擬處理數據庫等業務System.out.println(\"查詢\"+orderId+\"號訂單的狀態,如果已支付無需處理,如果未支付則回退庫存\");}}控制層代碼\@RestControllerpublic class OrderController {\@Autowiredprivate RabbitTemplate rabbitTemplate;\@RequestMapping(value = \"/place/{orderId}\",method =RequestMethod.GET)public String placeOrder(@PathVariable String orderId){//模擬service層處理System.out.println(\"處理訂單數據\...\");//將訂單id發送到訂單隊列rabbitTemplate.convertAndSend(\"order_exchange\",\"order_routing\",orderId);return \"下單成功,修改庫存\";}}
標簽:
搶先讀
- 焦點快報!塔瑞斯世界官網公測時間(dota2公測時間)
- 弘揚誠信文化 雁峰區開展“6.14信用記錄關愛日”宣傳
- 全球通訊!TüV萊茵與正泰綠色能源板塊在德舉行合作簽約儀式
- 視訊!國際油價料終結周線二連跌,產油國期待中國買需托市
- 智能化社區安全體驗館(智能化社區) 今熱點
- 三星 S23 系列系統迎來重大更新!國行版預計下周推送|世界信息
- 焦點播報:劍指智能駕駛 騰勢N7憋大招?
- 【焦點熱聞】2023年山西注冊會計師考試繳費入口已開通
- 魔幻!那個抱了梅西的球迷,穿的鞋登上淘寶熱銷榜首!網友:一雙好鞋,掌控全場…… 百事通
- 世界觀速訊丨英國首相稱AI是未來最大機會之一,力保英科技中心地位【附人工智能全球競爭力預測】
- 單位扣工資違反勞動法嗎
- 拉丁美洲的OmniMLS與LoneWolf合作提供完整的交易套件作為會員福利
- 熱門看點:5月份國民經濟延續恢復態勢
- 當前熱訊:動畫|寶“藏”朋友圈
- 國家發改委:大力推廣“信易貸”模式
- 【當前熱聞】79.12億+5.3萬㎡現房!中皋置業搖號競得亦莊新城X47R1地塊
- 搴旗(搴) 速讀
- 天天微資訊!北京:16項治療性輔助生殖技術納入醫保
- 當前熱文:有錢人都去買電動車了,降價潮后,豪華燃油車沒活路了?
- 延邊人民出版社大型辭書《朝鮮語大辭典》首發儀式舉行|精選
- 全球新消息丨填權是指什么意思 填權出現后如何應對
- 這次新能源汽車下鄉,共有69款車型參與!|每日視點
- 四川省1-5月居民消費價格(CPI)同比上漲0.8%
- 機電安裝工程行業市場分析及未來前景研究_天天即時看
- 拉菲尼亞:我將在下個賽季留在巴薩 歐冠是我們的目標 世界熱點
- 鄒平市黃山街道開展掃黃打非·護苗2023專項行動|天天觀點
- 我國經濟運行保持恢復態勢 重點在六方面發力
- 海南椰島(600238.SH):未涉及離島免稅業務|天天觀熱點
- 全球觀察:兩年以上基層工作經驗含兩年嗎(2年以上基層工作經歷什么意思)
- 每日觀察!支持科研項目找資金 助力企業機構找項目 深交所打通技術與資本兩個市場
- 雙下巴抽脂會導致臉部松弛嗎
- 三河市氣象臺更新高溫橙色預警【Ⅱ級/嚴重】【2023-06-16】
- 百隆東方: 目前,公司在新疆沒有生產加工基地,
- 當前焦點!商洛發布旅游優惠政策
- 祁陽市農產品監測保護市民“舌尖”安全
- 車輛違停碾壓盲道,司機到場得知被貼罰單后竟稱:那我不移了
- 重磅|“看中國”22省上線啟動!主題策劃發布!IPTV數據排行榜發布! 最新
- 當前關注:安陽紅旗渠機場飛行程序實地驗證試飛成功
- 要聞:做好防暑降溫、保障勞動者健康!廣州市總工會“送清涼”進基層
- 能鏈智電于翔:儲能技術推動新能源充電服務升級轉型-每日訊息
- 重慶巫溪“文旅+科技”融入巴蜀文旅走廊建設
- 夫唱婦隨!“國寶”朱鹮從浙江跨省定居江西婺源啦!|天天熱資訊
- 百隆東方: 百隆東方關于調整公司2021年第二期股票期權激勵計劃股票期權行權價格、激勵對象名單、期權數量并注銷部分已獲授但未行權的股票期權的公告
- 南昌一體化政務服務平臺再增3項特色應用場景_天天短訊
- 智慧交通多場景加速落地
- RabbitMQ快速使用代碼手冊
- 環球熱文:吉林省2023外貿企業匯率避險及融資需求對接會舉辦
- 貴陽首美整形醫院怎么樣 醫院真實案例分享
- 張家口:濃情“粽”動員 情暖環衛工 天天速讀
- 世界百事通!中國綠發舉辦共迎亞運倒計時100天騎行活動
- 「公安心向黨 護航新征程」國家反詐中心推出《2023版防范電信網絡詐騙宣傳手冊》 每日短訊
- 最新通化市各勞動仲裁委員會地址及咨詢電話名單一覽
- 天天熱門:西峽縣城區二中開展“我們的節日?端午節”主題系列活動
- 瓜叔必發:國足磨合存在問題,緬甸實力較差
- 加速電動化!法拉利動力總成工廠建成在即
- 每日焦點!香港考慮再放寬首置人群按揭成數 或接近零首付
- 上海昇思AI框架&大模型創新中心正式啟動 云從科技等首批22家單位入駐
- 【焦點熱聞】多省份公布高溫津貼發放標準:多地月標準達300元,海南最長發7個月
- 魏牌“雙旗艦SUV”亮相粵港澳大灣區車展-天天看點
- 聚焦數字化人才培養,2023微盟616數造零售大賽正式啟動|天天看點
- 【國際漫評】這是沒有新謠可造了嗎?|世界今日訊
- 菜滿園、果飄香!竹山這所“袖珍小學”有了“幸福農場” 環球簡訊
- 花樣滑冰項目單、雙人滑訓練營在首體進行 打造花滑選手互相學習提高的平臺|環球今日訊
- 中國開辟多國玉米進口通道
- 世界觀察:我國首條長江高鐵隧道開始盾構始發掘進
- 信銀理財智慧象合治進取1號年內跌7.66%-全球視訊
- 【三夏進行時】海報|三晉夏收農忙“豐”景
- 全球最資訊丨【三夏進行時】海報|三晉夏收農忙“豐”景
- “時尚中國”攝影大展延邊州精選展在延吉舉行
- 大連市將設立大連市政府引導母基金,首期規模100億元 環球通訊
- 中國大巴山(重慶·城口)消夏康養季6月21日啟動-當前消息
- 今日熱門!英偉達攜甜點級好物重磅加碼 RTX4060Ti顯卡在京東618賣爆
- 全球觀點:1-5月中國汽車類零售總額同比小幅增長
- 看熱訊:IWG集團簽署廣東首個管理項目 并首發HQ品牌
- 紫薇被容嬤嬤扎針臺詞(容嬤嬤扎針是什么梗) 環球消息
- 轉型氫能源未見成效,美錦能源投資活動凈流出超百億?|微資訊
- 2023城鎮職工醫保報銷流程是什么
- 世界快消息!中薇金融(00245):倪新光退任執行董事
- 重慶武隆區交通局二級調研員陳華涉嫌嚴重違紀違法接受審查調查
- 強奸罪追訴時效最長是多久_當前時訊
- 環球觀熱點:昇思開源社區理事會成立,基于昇思AI框架的全模態大模型“紫東.太初2.0”發布
- 歐洲主要股指集體高開
- 【全球播資訊】中交二航局舉辦2023世界交通運輸大會交通基礎設施工業化智能建造平行論壇
- 當健康成生意 主播應避免被流量“綁架”-天天要聞
- “五五購物節”火熱進行中,活動豐富、優惠多多
- 理想首款純電車型W01手繪圖 靈感源自鯨魚/明日公布車型名稱
- 當前滾動:甘肅隴西縣總工會:“1+17+N”構建新時代職工書屋矩陣
- 賽力斯股價連續上漲 李想稱問界M7“打殘”理想ONE
- 浙江邊檢總站開展“護航亞運”海空聯合巡航和應急處突演練-資訊
- 每日快看:私人山莊遭網紅闖入并渲染成鬼屋 房主發聲:丟失9萬余元財物,嚇得我都不敢回了
- 壁掛爐水壓2到3正常嗎為什么(壁掛爐水壓2到3正常嗎)
- 長沙小升初微機派位看成績嗎
- 甬金股份: 浙江甬金金屬科技股份有限公司公開發行可轉換公司債券受托管理事務報告(2022年度) 觀察
- 大貨車行駛途中起火自燃 淮安消防民警聯合撲救|時快訊
- 快看:尉氏縣舉行金融反詐知識宣傳活動
- 天天快消息!“小學老師被指課堂猥褻女生”續:警方未發現違法行為,不予立案
- 插入word圖片不顯示(word插入圖片顯示一條) 觀熱點
- 2023廈門個人社保繳費標準是多少錢一個月 焦點速看
- 是誰殺死了機械硬盤?不是固態硬盤!_世界實時
- 東吳醫院專家 女性不孕不育查什么_全球消息