rabbitMQ中发送和接收的都是字符串/字节数组类型的消息
实体类需实现
Serializable
接口;
生产者和消费者中的包名、类名、属性名必须一致;
生产者和消费者使用的queue队列一致
@Service public class MQService { @Resource private AmqpTemplate amqpTemplate; public void sendGoodsToMq(Dog dog){ //消息队列可以发送 字符串、字节数组、序列化对象 amqpTemplate.convertAndSend("","queue_A",dog); } }
@Component public class ConsumerService { @RabbitListener(queues = "queue_A") @RabbitHandler public void consumeMessage(Dog dog){ System.out.println("dog---"+dog); } }
实体类需实现
Serializable
接口;
生产者和消费者中的包名、类名、属性名必须一致;
生产者和消费者使用的queue队列一致
@Service public class MQService { @Resource private AmqpTemplate amqpTemplate; public void sendGoodsToMq(Dog dog){ //消息队列可以发送 字符串、字节数组、序列化对象 byte[] bytes = SerializationUtils.serialize(dog); amqpTemplate.convertAndSend("","queue_A",bytes); } }
@Component public class ConsumerService { @RabbitListener(queues = "queue_A") @RabbitHandler public void consumeMessage(byte[] bs){ Dog dog = (Goods) SerializationUtils.deserialize(bs); System.out.println("byte[]---"+dog); } }
对象的属性名需一致
@Service public class MQService { @Resource private AmqpTemplate amqpTemplate; public void sendGoodsToMq(Dog dog) throws JsonProcessingException { //消息队列可以发送 字符串、字节数组、序列化对象 ObjectMapper objectMapper = new ObjectMapper(); String msg = objectMapper.writeValueAsString(dog); amqpTemplate.convertAndSend("","queue_A",msg); } }
@Component public class ReceiveService { @RabbitListener(queues = "queue_A") @RabbitHandler public void receiveMsg(String msg) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); Dog dog = objectMapper.readValue(msg,Dog.class); System.out.println("String---"+msg); } }