赞
踩
拉取docker
镜像
docker pull rabbitmq:3-management
基础运行命令
docker run \
-e RABBITMQ_DEFAULT_USER=rabbitmq \
-e RABBITMQ_DEFAULT_PASS=rabbitmq \
--name rabbitmq \
-p 15672:15672 \
-p 5672:5672 \
-d \
rabbitmq:3-management
15672
是网页后台管理系统,5672
是给服务用的。
官方入门教程可以看这里RabbitMQ Tutorials — RabbitMQ
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
rabbitmq:
host: localhost # rabbitMQ的ip地址
port: 5672 # rabbitMQ服务端口
username: rabbitmq
password: rabbitmq
这边采用常用的消费者-生产者
模型,使用默认的Direct
类型exchange
。不懂的可以先继续学习rabbitmq
再来实践。
在消费者服务随便新建一个listener
@Slf4j
@Component
public class SpringRabbitListener {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "simple.queue"),
exchange = @Exchange(name = "simple.exchange"),
key = "simple"
))
public void listenSimpleQueue(String msg) {
log.info("消费者接收到simple.queue的消息:【" + msg + "】");
}
}
在生产者服务的Test
模块新建一个测试
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSendMessage2SimpleQueue() throws InterruptedException {
String message = "hello, spring amqp!";
rabbitTemplate.convertAndSend("simple.exchange", "simple", message);
}
}
先启动消费者。
登录http://localhost:15672/
,可以看到simple.exchange
和simple.queue
已被创建。
然后启动测试testSendMessage2SimpleQueue
,出现类似以下日志,消息发送成功。
12:17:43:771 INFO 21064 --- [ main] o.s.a.r.c.CachingConnectionFactory : Attempting to connect to: [localhost:5672]
12:17:43:808 INFO 21064 --- [ main] o.s.a.r.c.CachingConnectionFactory : Created new connection: rabbitConnectionFactory#50f40653:0/SimpleConnection@536d97f8 [delegate=amqp://rabbitmq@127.0.0.1:5672/, localPort= 59641]
消费者出现类似以下日志,收到消息。
12:17:31:074 INFO 8924 --- [ main] o.s.a.r.c.CachingConnectionFactory : Created new connection: rabbitConnectionFactory#2a27cb34:0/SimpleConnection@671facee [delegate=amqp://rabbitmq@127.0.0.1:5672/, localPort= 59634]
12:17:31:141 INFO 8924 --- [ main] cn.itcast.mq.ConsumerApplication : Started ConsumerApplication in 1.011 seconds (JVM running for 1.462)
12:17:43:848 INFO 8924 --- [ntContainer#0-1] c.i.mq.listener.SpringRabbitListener : 消费者接收到simple.queue的消息:【hello, spring amqp!】
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。