1. rabbitMQ的四种模式:可自行百度
以下是自己的理解,mq的消费模式无非是从 交换机 ,队列 入手的。
- 生产者-消费模式: 交换机不动(默认的交换机),设置队列(设置queue的key:qk【自定义】)
- 连接这个qk队列上的消费者收到生产者的消息
- 发布-订阅模式:设置交换机(设置exchange的key),队列不动。
- 连接这个交换机的队列所有的消费者都收到生产者的消息
- direct模式:设置交换机,设置队列。
- 连接这个交换机和这个队列上的消费者收到这个消息。
- topc模式:设置交换机,设置队列[自定义routkey的规则]。
- 根据队列key去模糊匹配上这个 交换机的上所有的队列key。
2.以下是使用干货
- 配置queue的名称
-
import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitMQConfig { @Bean public Queue myQueue() { return new Queue(Constant.RABBITMQ_ROUT_KEY); //这个key是字符串常量 } }
-
- 生产者
-
import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Date; /** * @author wupeng * @date 2019/6/21 13:44 * @desc MQ 生产者 */ @Component public class RabbitMQSender { @Autowired private AmqpTemplate rabbitTemplate; public void send() { String context = "hello " + new Date(); System.err.println("Sender : " + context); this.rabbitTemplate.convertAndSend(Constant.RABBITMQ_ROUT_KEY, context); } public void send(SRoomEntity sRoomEntity){ sRoomEntity = SRoomEntity.builder() .roomId("2") .useId("2") .projectId("2") .label("工程2") .originCode("hoc") .createTime(new Date()) .build(); System.err.println("Sender Object: " + sRoomEntity.toString()); this.rabbitTemplate.convertAndSend(Constant.RABBITMQ_ROUT_KEY,sRoomEntity); } }
-
- 消费者
-
import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; /** * @author wupeng * @date 2019/6/21 13:44 * @desc MQ 消费者 */ @Component @RabbitListener(queues = Constant.RABBITMQ_ROUT_KEY) public class RabbitMQReceiver { @RabbitHandler public void process(String hello) { System.err.println("Receiver : " + hello); } @RabbitHandler public void process(SRoomEntity sRoomEntity) { System.err.println("Receiver object : " + sRoomEntity.toString()); } }
以上使用一个发送字符串,一个发送对象的方法
-
-
总结:以上只是简单的 生产-消费者模式,使用的是默认的交换机模式