Docker安装RabbitMQ
1.搜索
docker search rabbitmq
2.安装
docker pull rabbitmq
3.启动
docker run -d --hostname my-rabbit --name rabbit -p 15672:15672 -p 5672:5672 rabbitmq
4.安装管理插件(两种写法)
进入容器内部docker exec -it rabbit/bin/bash
docker exec -it 1114cd9fcb59/bin/bash
5.安装插件
rabbitmq-plugins enable rabbitmq_management
6.查看插件情况
rabbitmq-plugins list
7.访问
用户名和密码用guest
8.使用步骤,maven项目
com.rabbitmq
amqp-client
4.2.0
org.slf4j
slf4j-simple
1.7.25
2.官网
https://www.rabbitmq.com/
3.编写生产者发送消息
//创建队列,发送消息
public static void sendMessage() throws Exception {
//获取连接
Connection connection = MessageUitl.getConnection();
//创建通道
Channel channel = connection.createChannel();
//声明创建队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//消息内容
String message = “Hello World!”;
channel.basicPublish(“”, QUEUE_NAME, null, message.getBytes());
System.out.println(“发送消息:” + message);
//关闭连接和通道
channel.close();
connection.close();
}
到RabbitMQ上查看
4.编写消费者
//消费者消费消息
public static void receiver() throws Exception {
//获取连接和通道
Connection connection = MessageUitl.getConnection();
Channel channel = connection.createChannel();
//声明通道
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body, “UTF-8”);
System.out.println(“接收到的消息:” + msg);
}
};
channel.basicConsume(QUEUE_NAME, consumer);
}
测试
再去运行生产者代码
发送三次,记得每次加1
下次整合SpringBoot