updated: 2021-10-20 20:46:13.145
url: https://hututu.fit/archives/java-rabbitmq-send-object
categories: java
tags: java | rabbitMQ
rabbitMQ中發送和接收的都是字符串/字節數組類型的消息
1.序列化對象
實體類需實現
Serializable
接口;
生產者和消費者中的包名、類名、屬性名必須一致;
生產者和消費者使用的queue隊列一致
1.1生產者
@Service
public class MQService {
@Resource
private AmqpTemplate amqpTemplate;
public void sendGoodsToMq(Dog dog){
//消息隊列可以發送 字符串、字節數組、序列化對象
amqpTemplate.convertAndSend("","queue_A",dog);
}
}
1.2消費者
@Component
public class ConsumerService {
@RabbitListener(queues = "queue_A")
@RabbitHandler
public void consumeMessage(Dog dog){
System.out.println("dog---"+dog);
}
}
2.序列化字節數組
實體類需實現
Serializable
接口;
生產者和消費者中的包名、類名、屬性名必須一致;
生產者和消費者使用的queue隊列一致
2.1 生產者
@Service
public class MQService {
@Resource
private AmqpTemplate amqpTemplate;
public void sendGoodsToMq(Dog dog){
//消息隊列可以發送 字符串、字節數組、序列化對象
byte[] bytes = SerializationUtils.serialize(dog);
amqpTemplate.convertAndSend("","queue_A",bytes);
}
}
2.2消費者
@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);
}
}
3.JSON字符串
對象的屬性名需一致
3.1 生產者
@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);
}
}
3.2消費者
@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);
}
}