进阶使用(转载):https://blog.csdn.net/wdcl2468/article/details/94228716
1.docker开启rabbitMQ
docker pull rabbitmq docker run -d -p 15672:15672 -p 5672:5672 -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin --name rabbitmq --hostname=rabbitmqhostone rabbitmq:latest
2.父工程引入依赖
org.springframework.boot spring-boot-starter-amqp
并在子工程的yml中进行相关配置
spring: rabbitmq: host: localhost port: 5672 virtual-host: / username: root password: 123456 listener: simple: prefetch: 3 #指消费者最多能预取的消息数,相当于先从mq中拿再慢慢处理,服务器的性能越高该数值越大
3.发送者类中加入RabbitTemplate并发送消息到队列中(前提是已经在rabbitMQ的控制台中新建类这个队列)
@RunWith(SpringRunner.class) @SpringBootTest public class springAMQPTest { @Autowired private RabbitTemplate rabbitTemplate; @Test public void sendMessage() { String queueName = "simple.queue"; String message = "another msg in simple"; rabbitTemplate.convertAndSend(queueName, message); } }
4.接受者使用@RabbitListener(queues = "队列名")监听队列
@Component public class SpringRabbitListener { @RabbitListener(queues = "simple.queue") public void listenSimpleQueue(String msg) { System.out.println("what receive is :"+msg); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)