1. 需要先安装 Erlang (Erlang 版本要和 RabbitMQ匹配 官网有匹配的版本https://www.rabbitmq.com/which-erlang.html )
2. 配置Erlang的环境变量
3. 在安装RabbitMQ(Erlang 版本要和 RabbitMQ匹配)
4.安装对应的RabbitMQ插件
测试安装完成之后输入 http://localhost:15672/
能进入如下页面表示环境配置已完成
默认的用户名和密码都是 guest
整合Springboot导入maven依赖
org.springframework.boot spring-boot-starter-amqp
配置application.yaml
#RabbitMQ
spring:
rabbitmq:
#服务器
host: localhost
#用户名
username: guest
#密码
password: guest
#虚拟主机
virtual-host: /
#端口
port: 5672
listener:
simple:
#消费者最小数量
concurrency: 10
#消费者最大数量
max-concurrency: 10
#限制消费者每次只能处理一条消息,处理完毕再继续下一条消息
prefetch: 1
#启动的时候是否默认启动容器,默认是true
auto-startup: true
#当消息被拒绝时,是否重新进入队列
default-requeue-rejected: true
template:
retry:
#发布重试,默认是false
enabled: true
#重试时间,默认1000ms
initial-interval: 1000ms
#重试最大次数 默认是3次
max-attempts: 3
#重试最大间隔时间,默认是10000ms
max-interval: 10000ms
#重试间隔乘数
multiplier: 1
配置config
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig{
//创建队列queue
@Bean
public Queue queue(){
return new Queue("queue",true);
}
}
生产者/发送者
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class MQSender {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send(Object msg){
log.info("发送消息:"+msg);
rabbitTemplate.convertAndSend("queue",msg);
}
}
消费者/接收者
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class MQReceiver {
//接收queue队列的消息
@RabbitListener(queues = "queue")
public void receiver(Object msg){
log.info("接收消息:"+msg);
}
}
controller层
import com.shao.seckill.rabbitmq.MQSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private MQSender mqSender;
@ResponseBody
@RequestMapping("/mq")
public void mq(){
mqSender.send("Hello");
}
}
测试结果
浏览器中访问对应url控制台输入日志消息
MQSender : 发送消息:Hello
MQReceiver : 接收消息:(Body:'Hello' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=queue, deliveryTag=1, consumerTag=amq.ctag-qwn10Ny_g9Cw3gCL5jNycg, consumerQueue=queue])
原理图解
P:生产者 C:消费者
这是最简单的一种模式想要了解更多交换机模式 https://blog.csdn.net/m0_58567231/article/details/122674383?spm=1001.2014.3001.5502



