一、使用RabbitMQ傳遞對象
RabbitMQ是消息隊列,發送和接收的都是字符串/字節數組類型的消息
1.1 使用序列化對象
要求:
傳遞的對象實現序列化接口
傳遞的對象的包名、類名、屬性名必須一致
-
消息提供者
@Service public class MQService { @Resource private AmqpTemplate amqpTemplate; public void sendGoodsToMq(Goods goods){ //消息隊列可以發送 字符串、字節數組、序列化對象 amqpTemplate.convertAndSend("","queue1",goods); } }
-
消息消費者
@Component @RabbitListener(queues = "queue1") public class ReceiveService { @RabbitHandler public void receiveMsg(Goods goods){ System.out.println("Goods---"+goods); } }
1.2 使用序列化字節數組
要求:
傳遞的對象實現序列化接口
傳遞的對象的包名、類名、屬性名必須一致
-
消息提供者
@Service public class MQService { @Resource private AmqpTemplate amqpTemplate; public void sendGoodsToMq(Goods goods){ //消息隊列可以發送 字符串、字節數組、序列化對象 byte[] bytes = SerializationUtils.serialize(goods); amqpTemplate.convertAndSend("","queue1",bytes); } }
-
消息消費者
@Component @RabbitListener(queues = "queue1") public class ReceiveService { @RabbitHandler public void receiveMsg(byte[] bs){ Goods goods = (Goods) SerializationUtils.deserialize(bs); System.out.println("byte[]---"+goods); } }
1.3 使用JSON字符串傳遞
要求:對象的屬性名一致
-
消息提供者
@Service public class MQService { @Resource private AmqpTemplate amqpTemplate; public void sendGoodsToMq(Goods goods) throws JsonProcessingException { //消息隊列可以發送 字符串、字節數組、序列化對象 ObjectMapper objectMapper = new ObjectMapper(); String msg = objectMapper.writeValueAsString(goods); amqpTemplate.convertAndSend("","queue1",msg); } }
-
消息消費者
@Component @RabbitListener(queues = "queue1") public class ReceiveService { @RabbitHandler public void receiveMsg(String msg) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); Goods goods = objectMapper.readValue(msg,Goods.class); System.out.println("String---"+msg); } }