养成看官网的好习惯: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
点击进去,可以看到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工程
happyland 父工程
happyland-customer 开心乐园顾客(消费)
happyland-market 开心乐园商店(生产)
一、pom依赖
父工程pom
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<modules>
<module>happyland-customer</module>
<module>happyland-market</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<groupId>com.happyland</groupId>
<artifactId>happyland</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<java.source.version>1.8</java.source.version>
<java.target.version>1.8</java.target.version>
<spring-boot.version>2.1.1.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
</build>
</project>
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
三、商店代码
====================商店接口===================
/**
* @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<String, Object> 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工具类================
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
5.2运行market项目,然后浏览器输入http://127.0.0.1:8082/product/add-product
此时代表商品成功数据成功
我们可以看到happyland的queue。
5.3运行顾客项目
可以看到顾客监听到商品到来,于是及时消费了。
此时控制台:
我们可以看到数据被及时消费了
关于routekey ,由于我采用的是默认交换机,所以routingkey其实没有什么意义,默认就是只要生产者往A队列发送数据,消费之就能从A队列取数据。