上一篇咱們講了 springboot 中如何使用 Redishtml
這一片,要寫關於 springboot 中如何使用 rabbitmqjava
附代碼:web
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 }
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 }
咱們能夠看到從消費者類中獲取到咱們推到隊列裏的消息redis
咱們從MQ的管理系統裏能夠看到咱們推的消息了spring
自此,RabbitMq 和 Redis 都寫完了sql