rabbitMq 快速入门
程序员文章站
2022-05-03 22:10:49
...
一、使用docker 安装 rabbitmq
1.在合适的位置创建 docker-compose.yml 文件
/local/docker/myCompose/rabbitMq
vim docker-compose.yml
version: "3.1"
services:
rabbitmq:
restart: always
image: rabbitmq:management
container_name: rabbitmq
ports:
- 5672:5672
- 15672:15672
environment:
TZ: Asia/Shanghai
RABBITMQ_DEFAULT_USER: rabbit
RABBITMQ_DEFAULT_PASS: 111111
volumes:
- ./data:/var/lib/rabbitmq
2.使用 docker-compose 构建 docker 容器
docker-compose up -d
3.查看容器
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b7ec95c13eaa rabbitmq:management "docker-entrypoint.s…" 4 hours ago Up 4 hours 4369/tcp, 5671/tcp, 0.0.0.0:5672->5672/tcp, 15671/tcp, 15691-15692/tcp, 25672/tcp, 0.0.0.0:15672->15672/tcp rabbitmq
二、项目使用 rabbitmq
1.pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
1.5 application.properties
spring.rabbitmq.host=172.16.104.217
spring.rabbitmq.port=5672
spring.rabbitmq.username=rabbit
spring.rabbitmq.password=111111
2.创建配置文件
note:是org.springframework.amqp.core.Queue的queue
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class mqConfig {
// 创建一个topic
@Bean
public Queue queue() {
// topic:helloRabbit
return new Queue("helloRabbit");
}
// 这里可以创建多个 topic
}
3.生产者
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class mqProvider {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(String message){
System.out.println("Provider:"+message);
// topic:helloRabbit
amqpTemplate.convertAndSend("helloRabbit",message);
}
}
5.执行发送
@SpringBootTest(classes = RabbitmqApplication.class)
class RabbitmqApplicationTests {
@Autowired
mqProvider mqProvider;
@Test
void contextLoads() {
for (int i = 0; i < 10; i++) {
mqProvider.send("hello my rabbit");
}
}
mq的后台将会在这里看到有消息产生
后台地址:http://172.16.104.217:15672/(我的测试机)
6.消费者 就会收到 他订阅的topic 的消息
@Component
// topic:helloRabbit
@RabbitListener(queues = "helloRabbit")
public class mqConsumer {
@RabbitHandler
public void process(String message){
System.out.println("Consumer:"+message);
}
}
上一篇: RabbitMQ快速入门(详细)
下一篇: flush() 缓冲输出流的缓冲区问题