RabbitMQ是居于AMQP协议的
RabbitMQ的安装
在docker中拉取镜像,docker pull rabbitmq:3.8.9-management
创建容器
docker run -di -p 5672:5672 -p 15672:15672 --name rabbitmq rabbitmq:3.8.9-management
注意,需要两个端口号
释放端口后
访问管理界面的地址就是 http://ip地址:15672,可以使用默认的账户登录,用户名和密码都guest
idea整合
创建springboot项目时选择web和spring for RabbitMQ的依赖
创建配置文件
spring:
rabbitmq:
host: 192.168.188.128
port: 5672
username: guest
password: guest
创建一个配置类
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SimpleQueueConfig {
//定义一个公有的队列名
private String simpleQueue = "spring.test.queue";
@Bean
public Queue simpleQueue() {
return new Queue(simpleQueue);
}
}
创建发送端
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SendMessage {
//引入RabbitMQ的模板引擎
@Autowired
private RabbitTemplate rabbitTemplate;
@RequestMapping("send")
public boolean send() {
try {
//传入队列名和要发送的消息
rabbitTemplate.convertAndSend("spring.test.queue", "哈啤酒,吃蛤蜊");
} catch (AmqpException e) {
e.printStackTrace();
return false;
}
return true;
}
}
- 创建接收端(监听器)
监听类的类中可以有多个监听方法
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class ResiverListener {
@RabbitListener(queues = "spring.test.queue")
public void resiverMessage(String msg){
System.out.println("消息是:"+msg);
}
}
启动主启动类然后访问发送端就可以获取到消息



