docker部署rabbitmq
shell
# management才有管理页面
docker pull rabbitmq:management
# 新建容器并运行
docker run \
-e RABBITMQ_DEFAULT_USER=admin \
-e RABBITMQ_DEFAULT_PASS=admin \
-v mq-plugins:/plugins \
--name mq \
--hostname mq \
-p 15672:15672 \
-p 5672:5672 \
-itd \
rabbitmq:management
# 查看运行状态
docker ps -a
导入RabbitMQ依赖
pom.xml
xml
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
提供者和消费者的配置
application.yml
yml
spring:
rabbitmq:
host: 192.168.137.139 # 主机名
port: 5672 # 端口
virtual-host: / # 虚拟主机
username: admin # 用户名
password: admin # 密码
注意执行顺序
:需要先使用consumer监听并创建队列,publisher再往里面添加队列才会有用,否则白添加队列
SimpleQueue
提供者: SimpleQueuePublisher.java
java
@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleQueuePublisher {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void simpleQueueTest() {
String msg = "hello, simple queue";
rabbitTemplate.convertAndSend("simple.queue", msg);
}
}
消费者:SimpleQueueConsumer.java
java
@Component
public class SimpleQueueConsumer {
@RabbitListener(queues = "simple.queue")
public void simpleQueueConsumer(String msg) {
System.out.println("simpleQueueConsumer: " + msg);
}
}
Work Queues
可加配置
application.yml
yml
spring:
rabbitmq:
listener:
simple: # simple类型
prefetch: 1 # consumer每次执行预取的数量
消费者:WorkQueueConsumer.java
java
@Component
public class WorkQueueConsumer {
@RabbitListener(queuesToDeclare = {@Queue(name = "work.queue")})
public void workQueue1Consumer(String msg) throws InterruptedException {
System.out.println("workQueue1Consumer: " + msg);
Thread.sleep(10);
}
@RabbitListener(queuesToDeclare = {@Queue(name = "work.queue")})
public void workQueue2Consumer(String msg) throws InterruptedException {
System.out.println("workQueue2Consumer: " + msg);
Thread.sleep(90);
}
}
提供者: WorkQueuePublisher.java
java
@RunWith(SpringRunner.class)
@SpringBootTest
public class WorkQueuePublisher {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void workQueueTest() {
for (int i = 1; i <= 100; i ++ ) {
String msg = "hello, work queue. " + i;
rabbitTemplate.convertAndSend("work.queue", msg);
}
}
}