RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费

养成看官网的好习惯:https://docs.spring.io/spring-boot/docs/2.1.2.RELEASE/reference/htmlsingle/

搭建环境:https://blog.csdn.net/qq_31615049/article/details/86556904

官方文档

在这里我们ctrl + f 搜索Rabbit  

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第1张图片

点击进去,可以看到Springboot对Rabbit的支持,下面我对这其中的文档做简单的翻译

33.2.1 RabbitMQ 支持

RabbitMQ基于AMQP协议进行通信的,请在application.properties添加如下配置

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=secret

33.2.2 发送消息

Spring的AMQPTemplate模板和AmqpAdmin是自动配置类,你可以将他们注入在你所希望的bean中。demo如下所示

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

	private final AmqpAdmin amqpAdmin;
	private final AmqpTemplate amqpTemplate;

	@Autowired
	public MyBean(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
		this.amqpAdmin = amqpAdmin;
		this.amqpTemplate = amqpTemplate;
	}

	// ...

}

......

33.2.3 接收消息

你可以在任何加了@RabbitListener(queues = "someQueue")的bean接收消息。例如:

@Component
public class MyBean {

	@RabbitListener(queues = "someQueue")
	public void processMessage(String content) {
		// ...
	}
}
....
其他的内容暂时不需要关注,仅仅实现一个最常见
==========================================================================================

动手实践:

创建maven工程

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第2张图片

happyland    父工程

    happyland-customer     开心乐园顾客(消费)

    happyland-market         开心乐园商店(生产)

一、pom依赖

父工程pom



    4.0.0
    pom

    
        happyland-customer
        happyland-market
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.1.RELEASE
    

    com.happyland
    happyland
    0.0.1-SNAPSHOT

    
        1.8
        1.8
        1.8
        2.1.1.RELEASE
    

    

        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
            com.rabbitmq
            amqp-client
            5.4.3
        

        
            org.springframework.amqp
            spring-rabbit
            2.1.3.RELEASE
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    exec
                
            
        
    


customer pom 和 market pom 保持系统默认生成即可。

二、market配置和customer配置

商店application.properties

# Spring boot application
spring.application.name = market_webserver
server.port = 8082

spring.rabbitmq.host=192.168.3.104
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/

spring.rabbitmq.listener.simple.acknowledge-mode=manual
spring.rabbitmq.listener.simple.concurrency=5
spring.rabbitmq.listener.simple.max-concurrency=10
#队列名
spring.rabbitmq.params.queue.name=springboot-happyland-queue
#交换机名
spring.rabbitmq.params.exchange.name=happyland-exchange
#路由key
spring.rabbitmq.params.route.key=happyland.product

顾客application.properties 

# Spring boot application
spring.application.name = customer_webserver
server.port = 8081
        
spring.rabbitmq.host=192.168.3.104
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/

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

spring.rabbitmq.params.queue.name=springboot-happyland-queue
spring.rabbitmq.params.exchange.name=happyland-exchange
spring.rabbitmq.params.route.key=happyland.product

三、商店代码

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第3张图片

====================商店接口===================
/**
 * @author: liujinghui
 * @create: 2018-12-29 22:35
 **/
public interface IProductService {
    void addProduct();
}
===================商店实现类==================
/**
 * @author: liujinghui
 * @create: 2018-12-29 22:36
 **/
@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private RabbitMQHelper rabbitMQHelper;

    @Override
    public void addProduct() {
        for(int i=0;i<10;i++){
            rabbitMQHelper.sendMessage("happy商品 No:"+i,new HashMap<>());
        }
    }
}
====================商店Controller=====================
/**
 * @author: liujinghui
 * @create: 2018-12-29 22:36
 **/

@Controller()
@RequestMapping("/product")
public class ProductWeb {

    @Autowired
    private IProductService iProdctService;

    @RequestMapping("/add-product")
    @ResponseBody
    public String addProduct(){
        iProdctService.addProduct();
        return "添加十件商品";
    }
}

===============商店RabbitMQ工具类=====================
package com.happyland.happylandmarket.RabbitMQHelper;

import com.rabbitmq.client.ConfirmCallback;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: liujinghui
 * @create: 2019-01-20 12:34
 **/
@Component
public class RabbitMQHelper {

    private final AmqpAdmin amqpAdmin;
    private final AmqpTemplate amqpTemplate;

    @Value("${spring.rabbitmq.params.exchange.name}")
    private String exchangeName;
    @Value("${spring.rabbitmq.params.queue.name}")
    private String queueName;
    @Value("${spring.rabbitmq.params.route.key}")
    private String routeKey;


    @Autowired
    public RabbitMQHelper(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
        this.amqpAdmin = amqpAdmin;
        this.amqpTemplate = amqpTemplate;
    }

    public void sendMessage(String content, Map params){
        amqpAdmin.declareExchange(new DirectExchange(exchangeName,false,false));
        amqpAdmin.declareQueue(new Queue(queueName,false));
        amqpAdmin.declareBinding(new Binding(queueName,
                Binding.DestinationType.QUEUE,
                exchangeName,
                routeKey,
                new HashMap<>()));
        MessageHeaders messageHeaders = new MessageHeaders(params);
        Message message = MessageBuilder.createMessage(content, messageHeaders);
        amqpTemplate.convertAndSend(exchangeName, routeKey, message);
    }

}

四、顾客代码

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第4张图片

=================顾客RabbitMQ工具类================
package com.happyland.happylandcustomer.mqhelper;

import com.rabbitmq.client.Channel;
import com.sun.org.apache.xpath.internal.operations.String;
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;

/**
 * @program: com.happyland.happylandcustomer.mqhelper
 * @description:
 * @author: liujinghui
 * @create: 2019-01-20 12:34
 **/
@Component
public class RabbitMQHelper {

    @RabbitListener(queues = "${spring.rabbitmq.params.queue.name}")
    @RabbitHandler
    public void processMessage(Message message, Channel channel) throws IOException {
        Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);
        System.out.println(message.getPayload().toString());
    }

}

五、运行测试

5.1打开控制台 http://192.168.3.104:15672/#/queues

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第5张图片

5.2运行market项目,然后浏览器输入http://127.0.0.1:8082/product/add-product

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第6张图片

此时代表商品成功数据成功

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第7张图片

我们可以看到happyland的queue。

5.3运行顾客项目

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第8张图片

可以看到顾客监听到商品到来,于是及时消费了。

此时控制台:

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第9张图片

我们可以看到数据被及时消费了

关于routekey ,由于我采用的是默认交换机,所以routingkey其实没有什么意义,默认就是只要生产者往A队列发送数据,消费之就能从A队列取数据。

RabbitMQ - RabbitMQ 3.7.10 与 springboot2.1.1整合 实现最简单的生产消费_第10张图片

你可能感兴趣的:(RabbitMQ)