1. 程式人生 > >Springboot整合 二 集成 rabbitmq

Springboot整合 二 集成 rabbitmq

nal pla frame param 指定 .get 配置 tor fan

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

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

2. 項目啟動配置

技術分享圖片
大家可以看到上圖中的config包,這裏就是相關配置類

下面,就這三個配置類,做下說明:(這裏需要大家對RabbitMQ有一定的了解,知道生產者、消費者、消息交換機、隊列等)

ExchangeConfig 消息交換機配置

package com.space.rabbitmq.config;
 
import org.springframework.amqp.core.DirectExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * 消息交換機配置  可以配置多個
 * @author zhuzhe
 * @date 2018/5/25 15:40
 * @email [email protected]
 
*/ @Configuration public class ExchangeConfig { /** * 1.定義direct exchange,綁定queueTest * 2.durable="true" rabbitmq重啟的時候不需要創建新的交換機 * 3.direct交換器相對來說比較簡單,匹配規則為:如果路由鍵匹配,消息就被投送到相關的隊列 * fanout交換器中沒有路由鍵的概念,他會把消息發送到所有綁定在此交換器上面的隊列中。 * topic交換器你采用模糊匹配路由鍵的原則進行轉發消息到隊列中 * key: queue在該direct-exchange中的key值,當消息發送給direct-exchange中指定key為設置值時, * 消息將會轉發給queue參數指定的消息隊列
*/ @Bean public DirectExchange directExchange(){ DirectExchange directExchange = new DirectExchange(RabbitMqConfig.EXCHANGE,true,false); return directExchange; } }

QueueConfig 隊列配置
package com.space.rabbitmq.config;
 
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * 隊列配置  可以配置多個隊列
 * @author zhuzhe
 * @date 2018/5/25 13:25
 * @email [email protected]
 */
@Configuration
public class QueueConfig {
 
    @Bean
    public Queue firstQueue() {
        /**
         durable="true" 持久化 rabbitmq重啟的時候不需要創建新的隊列
         auto-delete 表示消息隊列沒有在使用時將被自動刪除 默認是false
         exclusive  表示該消息隊列是否只在當前connection生效,默認是false
         */
        return new Queue("first-queue",true,false,false);
    }
 
    @Bean
    public Queue secondQueue() {
        return new Queue("second-queue",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配置
 * @author zhuzhe
 * @date 2018/5/25 13:37
 * @email [email protected]
 */
@Configuration
public class RabbitMqConfig {
 
    /** 消息交換機的名字*/
    public static final String EXCHANGE = "exchangeTest";
    /** 隊列key1*/
    public static final String ROUTINGKEY1 = "queue_one_key1";
    /** 隊列key2*/
    public static final String ROUTINGKEY2 = "queue_one_key2";
 
    @Autowired
    private QueueConfig queueConfig;
    @Autowired
    private ExchangeConfig exchangeConfig;
 
    /**
     * 連接工廠
     */
    @Autowired
    private ConnectionFactory connectionFactory;
 
    /**
     將消息隊列1和交換機進行綁定
     */
    @Bean
    public Binding binding_one() {
        return BindingBuilder.bind(queueConfig.firstQueue()).to(exchangeConfig.directExchange()).with(RabbitMqConfig.ROUTINGKEY1);
    }
 
    /**
     * 將消息隊列2和交換機進行綁定
     */
    @Bean
    public Binding binding_two() {
        return BindingBuilder.bind(queueConfig.secondQueue()).to(exchangeConfig.directExchange()).with(RabbitMqConfig.ROUTINGKEY2);
    }
 
    /**
     * 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); //設置確認模式手工確認
        return simpleMessageListenerContainer;
    }
 
    /**
     * 定義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();
    }
 
}

消息回調

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 [email protected]
 */
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 [email protected]
 */
@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 [email protected]
 */
@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.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 [email protected]
 */
@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 [email protected]
*/
@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;
}
}

Springboot整合 二 集成 rabbitmq