养成看官网的好习惯: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的支持,下面我对这其中的文档做简单的翻译
RabbitMQ基于AMQP协议进行通信的,请在application.properties添加如下配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=secret
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;
}
// ...
}
......
你可以在任何加了@RabbitListener(queues = "someQueue")的bean接收消息。例如:
@Component
public class MyBean {
@RabbitListener(queues = "someQueue")
public void processMessage(String content) {
// ...
}
}
.... 其他的内容暂时不需要关注,仅仅实现一个最常见 ==========================================================================================
创建maven工程
happyland 父工程
happyland-customer 开心乐园顾客(消费)
happyland-market 开心乐园商店(生产)
父工程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 保持系统默认生成即可。
商店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 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队列取数据。