Springboot整合二 集成 rabbitmq

一、在application.yml文件中進行RabbitMQ的相關配置
先上代碼java

spring:
  rabbitmq:
    host: 192168.21.11
    port: 5672
    username: guest
    password: password
    publisher-confirms: true    #  消息發送到交換機確認機制,是否確認回調
  virtual-host: / #默認主機

#自定義參數
defineProps:
 rabbitmq:
  wechat:
   template:
    topic: wxmsg.topic
    queue: wxmsg.queue
    # *表號匹配一個word,#匹配多個word和路徑,路徑之間經過.隔開
    queue1_pattern: wxmsg.message.exchange.queue.#
    # *表號匹配一個word,#匹配多個word和路徑,路徑之間經過.隔開
    queue2_pattern: wxmsg.message.exchange.queue.#

 

2. 項目啓動配置web


       你們能夠看到上圖中的config包,這裏就是相關配置類

下面,就這三個配置類,作下說明:(這裏須要你們對RabbitMQ有必定的瞭解,知道生產者、消費者、消息交換機、隊列等)redis

 

ExchangeConfig    消息交換機配置spring

package com.space.rabbitmq.config;
 
import org.springframework.amqp.core.DirectExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * 消息交換機配置  能夠配置多個
 */
@Configuration
public class ExchangeConfig {
    @Value("${defineProps.rabbitmq.wechat.template.topic}")
    private String templateTopic;

    /**
     *   1.定義topic exchange,綁定路由
     *   2.direct交換器相對來講比較簡單,匹配規則爲:若是路由鍵匹配,消息就被投送到相關的隊列
     *     fanout交換器中沒有路由鍵的概念,他會把消息發送到全部綁定在此交換器上面的隊列中。
     *     topic交換器你採用模糊匹配路由鍵的原則進行轉發消息到隊列中
     *   3.durable="true" rabbitmq重啓的時候不須要建立新的交換機
     *   4.autoDelete:false ,默認不自動刪除
     *   5.key: queue在該topic exchange中的key值,當消息符合topic exchange中routing_key規則,
     *   消息將會轉發給queue參數指定的消息隊列
     */
    public TopicExchange topicExchange(){
        return new TopicExchange(templateTopic, true, false);
    } }

QueueConfig 隊列配置
package com.space.rabbitmq.config;
 
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * 隊列配置  能夠配置多個隊列
 */
@Configuration
public class QueueConfig {
 
    @Bean
    public Queue firstQueue() {
        /**
         durable="true" 持久化 rabbitmq重啓的時候不須要建立新的隊列
         auto-delete 表示消息隊列沒有在使用時將被自動刪除 默認是false
         exclusive  表示該消息隊列是否只在當前connection生效,默認是false
         */
        return new Queue("queue1",true,false,false);
    }
 
    @Bean
    public Queue secondQueue() {
        return new Queue("queue2",true,false,false);
    }
}

RabbitMqConfig RabbitMq配置
package com.space.rabbitmq.config;
 
import com.space.rabbitmq.mqcallback.MsgSendConfirmCallBack;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * RabbitMq配置
 */
@Configuration
public class RabbitMqConfig {
 
    @Value("${spring.rabbitmq.host}")
    private String host;
    @Value("${spring.rabbitmq.port}")
    private int port;
    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;
    @Value("${spring.rabbitmq.virtual-host}")
    private String vhost;
    
    @Value("${defineProps.rabbitmq.wechat.template.
queue1_pattern}")
    private String
queue1_pattern;
    @Value("${defineProps.rabbitmq.wechat.template.
queue2_pattern}")
    private String
queue2_pattern; @Autowired
private QueueConfig queueConfig; @Autowired private ExchangeConfig exchangeConfig;
/**
* 鏈接工廠
*/
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost(vhost);
return connectionFactory;
}

@Bean
public RabbitTemplate rabbitTemplate(){
return new RabbitTemplate(connectionFactory());
}
/** 將消息隊列1和交換機進行綁定 */ @Bean public Binding binding_one() { return BindingBuilder.bind(queueConfig.firstQueue()).to(exchangeConfig.topicExchange()).with(queue1_pattern); } /** * 將消息隊列2和交換機進行綁定 */ @Bean public Binding binding_two() { return BindingBuilder.bind(queueConfig.secondQueue()).to(exchangeConfig.topicExchange()).with(queue2_pattern); } /** * queue listener 觀察 監聽模式 * 當有消息到達時會通知監聽在對應的隊列上的監聽對象 * @return */ @Bean public SimpleMessageListenerContainer simpleMessageListenerContainer_one(){ SimpleMessageListenerContainer simpleMessageListenerContainer = new SimpleMessageListenerContainer(connectionFactory); simpleMessageListenerContainer.addQueues(queueConfig.firstQueue()); simpleMessageListenerContainer.setExposeListenerChannel(true); simpleMessageListenerContainer.setMaxConcurrentConsumers(5); simpleMessageListenerContainer.setConcurrentConsumers(1); simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL); //設置確認模式手工確認 simpleMessageListenerContainer.setMessageListener(wechatPushMessageListener());
return simpleMessageListenerContainer; }

/**
* 配置消費者bean
* @return
*/
@Bean
public WechatPushMessageConsumer wechatPushMessageListener(){
return new WechatPushMessageConsumer(redisUtil, mqMsgExceptionRemote, wechatAppID, wechatAppSecret);
}
/** * 定義rabbit template用於數據的接收和發送 * @return */ @Bean public RabbitTemplate rabbitTemplate() { RabbitTemplate template = new RabbitTemplate(connectionFactory); /**若使用confirm-callback或return-callback, * 必需要配置publisherConfirms或publisherReturns爲true * 每一個rabbitTemplate只能有一個confirm-callback和return-callback */ template.setConfirmCallback(msgSendConfirmCallBack()); //template.setReturnCallback(msgSendReturnCallback()); /** * 使用return-callback時必須設置mandatory爲true,或者在配置中設置mandatory-expression的值爲true, * 可針對每次請求的消息去肯定’mandatory’的boolean值, * 只能在提供’return -callback’時使用,與mandatory互斥 */ // template.setMandatory(true); return template; } /** * 消息確認機制 * Confirms給客戶端一種輕量級的方式,可以跟蹤哪些消息被broker處理, * 哪些可能由於broker宕掉或者網絡失敗的狀況而從新發布。 * 確認而且保證消息被送達,提供了兩種方式:發佈確認和事務。(二者不可同時使用) * 在channel爲事務時,不可引入確認模式;一樣channel爲確認模式下,不可以使用事務。 * @return */ @Bean public MsgSendConfirmCallBack msgSendConfirmCallBack(){ return new MsgSendConfirmCallBack(); } }

 

消息回調express

package com.space.rabbitmq.mqcallback;
 
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
 
/**
 * 消息發送到交換機確認機制
 * @author zhuzhe
 * @date 2018/5/25 15:53
 * @email 1529949535@qq.com
 */
public class MsgSendConfirmCallBack implements RabbitTemplate.ConfirmCallback {
 
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        System.out.println("MsgSendConfirmCallBack  , 回調id:" + correlationData);
        if (ack) {
            System.out.println("消息消費成功");
        } else {
            System.out.println("消息消費失敗:" + cause+"\n從新發送");
        }
    }
}

 

生產者/消息發送者

package com.space.rabbitmq.sender;
 
import com.space.rabbitmq.config.RabbitMqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.UUID;
 
/**
 * 消息發送  生產者1
 * @author zhuzhe
 * @date 2018/5/25 14:28
 * @email 1529949535@qq.com
 */
@Slf4j
@Component
public class FirstSender {
 
    @Autowired
    private RabbitTemplate rabbitTemplate;
 
    /**
     * 發送消息
     * @param uuid
     * @param message  消息
     */
    public void send(String uuid,Object message) {
        CorrelationData correlationId = new CorrelationData(uuid);
        rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE, RabbitMqConfig.ROUTINGKEY2,
                message, correlationId);
    }
}

消費者

方式一(使用註解): 

package com.space.rabbitmq.receiver; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component;
/** * 消息消費者1 * @author zhuzhe * @date 2018/5/25 17:32 * @email 1529949535@qq.com */ @Component public class FirstConsumer { @RabbitListener(queues = {"first-queue","second-queue"}, containerFactory = "rabbitListenerContainerFactory") public void handleMessage(String message) throws Exception { // 處理消息 System.out.println("FirstConsumer {} handleMessage :"+message); } }
方式二(利用配置):
package com.space.rabbitmq.receiver; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component;
/** * 消息消費者1 */public class WechatPushMessageConsumer extends BaseMessageConsumer implements ChannelAwareMessageListener
@Override
public void onMessage(Message message, Channel channel) throws Exception {
      System.out.println("接收到的消息:" + message.getBody());
    }
}

 

消息接收兩種方式:

@RabbitListener @RabbitHandler 及 消息序列化
參看資料: https://www.jianshu.com/p/911d987b5f11

測試

package com.space.rabbitmq.controller;
 
import com.space.rabbitmq.sender.FirstSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.UUID;
 
/**
 * @author zhuzhe
 * @date 2018/5/25 16:00
 * @email 1529949535@qq.com
 */
@RestController
public class SendController {
 
    @Autowired
    private FirstSender firstSender;
 
    @GetMapping("/send")
    public String send(String message){
        String uuid = UUID.randomUUID().toString();
        firstSender.send(uuid,message);
        return uuid;
    }
}

 

 

 

 

 

 

 

 

package com.space.rabbitmq.controller;
 
import com.space.rabbitmq.sender.FirstSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.UUID;
 
/**
 * @author zhuzhe
 * @date 2018/5/25 16:00
 * @email 1529949535@qq.com
 */
@RestController
public class SendController {
 
    @Autowired
    private FirstSender firstSender;
 
    @GetMapping("/send")
    public String send(String message){
        String uuid = UUID.randomUUID().toString();
        firstSender.send(uuid,message);
        return uuid;
    }
}

網絡

topicExchange
相關文章
相關標籤/搜索