rabbitmq-springboot整合

PS:生產者和消費者在兩個項目中

生產者

1、maven依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

2.yml

spring:
  application:
    name: test-demo
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    virtual-host: /adminPy
    username: admin_py
    password: 123456
    connection-timeout: 1500ms
    #生產端監聽
    publisher-confirms: true
    #生產端監聽
    publisher-returns: true
    template:
      mandatory: true #該屬性必須設置爲true,並與publisher-returns一起聯合使用纔可以
    publisher-confirm-type: simple

3、代碼

import com.example.springcloud.entity.Order;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * Created by py
 * 2020/4/25
 */
@Component
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    final ConfirmCallback confirmCallback =  new ConfirmCallback(){
        @Override
        public void confirm(CorrelationData correlationData, boolean b, String s) {
            System.err.println("correlationData: " + correlationData);
            System.err.println("ack: " + b);
            if(!b){
                System.err.println("異常處理....");
            }
        }
    };


    //回調函數: return返回
    final ReturnCallback returnCallback = new ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,
                                    String exchange, String routingKey) {
            try {
                String body = new String(message.getBody(), "utf-8");
                System.err.println("body:"+body);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            System.err.println("return exchange: " + exchange + ", routingKey: "
                    + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
        }
    };

    //發送消息方法調用: 構建Message消息
    public void send(Object message, Map<String, Object> properties) throws Exception {
        MessageHeaders mhs = new MessageHeaders(properties);
        Message msg = MessageBuilder.createMessage(message, mhs);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        //id + 時間戳 全局唯一
        CorrelationData correlationData = new CorrelationData("MSG-"+ new Date().getTime());
        rabbitTemplate.convertAndSend("springboot-exchange", "springboot.abc", msg, correlationData);
    }

    //發送消息方法調用: 構建自定義對象消息
    //todo 推送對象的話生產者和消費者對象的包名必須完全一致才行,否則消費者無法接收對象數據
    public void sendOrder(Order order) throws Exception {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        //id + 時間戳 全局唯一
        CorrelationData correlationData = new CorrelationData("order-"+ new Date().getTime());
        rabbitTemplate.convertAndSend("exchange-2", "*", order, correlationData);
    }
}
import com.example.springcloud.entity.Order;
import com.example.springcloud.testdemo.rabbitConfig.RabbitSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by py
 * 2020/4/25
 */
@RequestMapping("/rabbit")
@RestController
public class RabbitController {

    @Autowired
    private RabbitSender rabbitSender;
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    @RequestMapping("/send1")
    public String senderMsg() throws Exception {
        Map<String, Object> properties = new HashMap<>();
        properties.put("number", "12345");
        properties.put("send_time", simpleDateFormat.format(new Date()));
        rabbitSender.send("Hello RabbitMQ For Spring Cloud",properties);
        return "信息發送成功";
    }

    @RequestMapping("/send2")
    public String sender2() throws Exception {
        Order order = new Order(1,"this is order");
        rabbitSender.sendOrder(order);
        return "信息發送成功";
    }
}

消費者:

1、maven依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

2、yml

spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=/adminPy
spring.rabbitmq.username=admin_py
spring.rabbitmq.password=123456
spring.rabbitmq.connection-timeout=1500ms
#手動回覆信息
spring.rabbitmq.listener.direct.acknowledge-mode=manual
#設置併發數量
spring.rabbitmq.listener.simple.concurrency=5
#設置最大併發數量
spring.rabbitmq.listener.simple.max-concurrency=10

3、代碼

import com.example.springcloud.entity.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * Created by py
 * 2020/4/26
 */
@Component
public class RabbitRecver {

    @RabbitListener(bindings=@QueueBinding(
            value = @Queue(name = "springboot-queue",declare = "true",durable = "true",exclusive = "false"),
            exchange = @Exchange(name = "springboot-exchange",type = "topic"),
            key = "#"
    ))
    @RabbitHandler
    public void Recver(Message message, @Headers Map<String, Object> heards, Channel channel){
        System.out.println(message.getPayload());
        //所有消息處理後必須進行消息的ack,channel.basicAck()
        Long tag = (Long)heards.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(tag , false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(bindings =
        @QueueBinding(
                value = @Queue(value = "springboot.def",durable = "true",exclusive = "false"),
                exchange = @Exchange(name = "exchange-2",type = "direct"),
                key = "*"
        )
    )
    @RabbitHandler
    public void RecverOrder(@Payload Order order, Channel channel, @Headers Map<String,Object> heards) throws IOException {
        System.out.println(order);
        Long tag = (Long) heards.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(tag,false);
    }
}

PS:注意生產者和消費在order對象的包名路徑完全一致,不一致消費者無法正常接收信息。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章