上一篇我们讲了 springboot 中如何使用 Redis
这一片,要写关于 springboot 中如何使用 rabbitmq
附代码:
1 package com.ncat.webdemo.rabbitmq; 2 3 import org.springframework.amqp.core.AmqpAdmin; 4 import org.springframework.amqp.core.AmqpTemplate; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Component; 7 8 import java.util.Map; 9 10 @Component 11 public class Producer { 12 @Autowired 13 private AmqpTemplate amqpTemplate; 14 15 @Autowired 16 private AmqpAdmin amqpAdmin; 17 18 /** 19 * @param routingKey 路由关键字 20 * @param msg 消息体 21 */ 22 public void sendDirectMsg(String routingKey, String msg) { 23 amqpTemplate.convertAndSend(routingKey, msg); 24 } 25 26 /** 27 * @param exchange 交换机 28 * @param routingKey 路由关键字 29 * @param msg 消息体 30 */ 31 public void sendExchangeMsg(String exchange, String routingKey, String msg) { 32 amqpTemplate.convertAndSend(exchange, routingKey, msg); 33 } 34 35 /** 36 * @param exchange 交换机 37 * @param msg 路由关键字 38 * @param map 消息headers属性 39 */ 40 public void sendHeadersMsg(String exchange, String msg, Map<String, Object> map) { 41 amqpTemplate.convertAndSend(exchange, null, msg, message -> { 42 message.getMessageProperties().getHeaders().putAll(map); 43 return message; 44 }); 45 } 46 47 } View Code 1 package com.ncat.webdemo.rabbitmq; 2 3 import org.springframework.amqp.rabbit.annotation.RabbitListener; 4 import org.springframework.stereotype.Component; 5 6 @Component 7 public class Consumer { 8 @RabbitListener(queues = "Qu_CoinTest") 9 public void subscribeMessage(String msg) { 10 System.out.println(msg); 11 } 12 } View Code
我们可以看到从消费者类中获取到我们推到队列里的消息
我们从MQ的管理系统里可以看到我们推的消息了
自此,RabbitMq 和 Redis 都写完了
转载于:https://www.cnblogs.com/nigthcat/p/11458829.html
相关资源:1 SpringBoot整合RabbitMQ-整合配置篇-源码数据库