RabbitMQ之集成springcloud项目

前言

本次就是创建springboot项目来模拟如何在springcloud项目中使用RabbitMQ

springcloud项目

common(公共模块)

在这里插入图片描述
pom.xml:

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

Order

package com.liwangwang.rabbitmqcommon.entity;

import java.io.Serializable;


public class Order implements Serializable {

    private String id;
    private String name;

    public Order() {
    }
    public Order(String id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }


}

consumer(消费端)

在这里插入图片描述
pom.xml所加上得依赖:

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

pom.xml依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.liwangwang</groupId>
    <artifactId>rabbitmq-springcloud-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rabbitmq-springcloud-consumer</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>com.liwangwang</groupId>
            <artifactId>rabbitmq-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

yml配置文件(当然看样子都是properties)

spring.rabbitmq.addresses=192.168.47.134:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=15000

spring.rabbitmq.listener.simple.acknowledge-mode=manual
spring.rabbitmq.listener.simple.concurrency=5
spring.rabbitmq.listener.simple.max-concurrency=10

spring.rabbitmq.listener.order.queue.name=queue-2
spring.rabbitmq.listener.order.queue.durable=true
spring.rabbitmq.listener.order.exchange.name=exchange-2
spring.rabbitmq.listener.order.exchange.durable=true
spring.rabbitmq.listener.order.exchange.type=topic
spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions=true
spring.rabbitmq.listener.order.key=springboot.*


RabbitReceiver

package com.liwangwang.rabbitmqspringcloudconsumer.conusmer;

import com.liwangwang.rabbitmqcommon.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.util.Map;

@Component
public class RabbitReceiver {

   
   @RabbitListener(bindings = @QueueBinding(
         value = @Queue(value = "queue-1", durable="true"),
         exchange = @Exchange(value = "exchange-1",  durable="true", type= "topic", ignoreDeclarationExceptions = "true"),
         key = "springboot.*"
         )
   )
   @RabbitHandler
   public void onMessage(Message message, Channel channel) throws Exception {
      System.err.println("--------------------------------------");
      System.err.println("消费端Payload: " + message.getPayload());
      Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);//amqp_deliveryTag

       // 手动签收,重回队列
//    channel.basicNack(deliveryTag, false, true);
       //手工ACK
      channel.basicAck(deliveryTag, false);
   }
   
   
   /**
    * 
    *     spring.rabbitmq.listener.order.queue.name=queue-2
      spring.rabbitmq.listener.order.queue.durable=true
      spring.rabbitmq.listener.order.exchange.name=exchange-1
      spring.rabbitmq.listener.order.exchange.durable=true
      spring.rabbitmq.listener.order.exchange.type=topic
      spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions=true
      spring.rabbitmq.listener.order.key=springboot.*
    * @param order
    * @param channel
    * @param headers
    * @throws Exception
    */
   @RabbitListener(bindings = @QueueBinding(
         value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}", 
         durable="${spring.rabbitmq.listener.order.queue.durable}"),
         exchange = @Exchange(value = "${spring.rabbitmq.listener.order.exchange.name}", 
         durable="${spring.rabbitmq.listener.order.exchange.durable}", 
         type= "${spring.rabbitmq.listener.order.exchange.type}", 
         ignoreDeclarationExceptions = "${spring.rabbitmq.listener.order.exchange.ignoreDeclarationExceptions}"),
         key = "${spring.rabbitmq.listener.order.key}"
         )
   )
   @RabbitHandler
   public void onOrderMessage(@Payload Order order, Channel channel,
         @Headers Map<String, Object> headers) throws Exception {
      System.err.println("--------------------------------------");
      System.err.println("消费端order: " + order.getId());
      Long deliveryTag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
      //手工ACK
      channel.basicAck(deliveryTag, false);
   }
   
   
}

第一种方式:
在这里插入图片描述
第二种方式:
在这里插入图片描述

producer(生产端)

在这里插入图片描述

pom.xml加依赖

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

yml配置文件:

spring.rabbitmq.addresses=192.168.47.134:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
spring.rabbitmq.connection-timeout=15000

spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.publisher-returns=true
spring.rabbitmq.template.mandatory=true


RabbitSender

package com.liwangwang.rabbitmqspringcloudproducer.producer;

import com.liwangwang.rabbitmqcommon.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.util.Map;


@Component
public class RabbitSender {

   //自动注入RabbitTemplate模板类
   @Autowired
   private RabbitTemplate rabbitTemplate;  
   
   //回调函数: confirm确认,对于broker来说如果没有被签收或签收,都会给生产端发消息
   final ConfirmCallback confirmCallback = new ConfirmCallback() {
      @Override
      public void confirm(CorrelationData correlationData, boolean ack, String cause) {
         System.err.println("correlationData: " + correlationData);
         System.err.println("confirm确认ack: " + ack);
         if(!ack){
            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) {
         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("1234567890");
      rabbitTemplate.convertAndSend("exchange-1", "springboot.abc", msg, correlationData);
   }
   
   //发送消息方法调用: 构建自定义对象消息
   public void sendOrder(Order order) throws Exception {
      rabbitTemplate.setConfirmCallback(confirmCallback);
      rabbitTemplate.setReturnCallback(returnCallback);
      //id + 时间戳 全局唯一 
      CorrelationData correlationData = new CorrelationData("0987654321");
      rabbitTemplate.convertAndSend("exchange-2", "springboot.def", order, correlationData);
   }
   
}

两个机制,可以在上章找到:
在这里插入图片描述
发送消息得方法:
(所以我们到时候直接调用指定方法就可以获取到了)

在这里插入图片描述

测试

先把消费者服务打开,然后调用测试方法发送消息即可

自行测试:

RabbitmqSpringcloudProducerApplicationTests

package com.liwangwang.rabbitmqspringcloudproducer;

import com.liwangwang.rabbitmqcommon.entity.Order;

import com.liwangwang.rabbitmqspringcloudproducer.producer.RabbitSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitmqSpringcloudProducerApplicationTests {

    @Autowired
    private RabbitSender rabbitSender;

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

    @Test
    public void testSender1() 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 Boot!", properties);
    }

    @Test
    public void testSender2() throws Exception {
        Order order = new Order("001", "第一个订单");
        rabbitSender.sendOrder(order);
    }

}

测试一:
在这里插入图片描述
结果:
在这里插入图片描述
测试二:

在这里插入图片描述
结果:

在这里插入图片描述

后记

暂无实战内容;

发布了143 篇原创文章 · 获赞 136 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43943548/article/details/103463125