一: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);
}
}
-----------------------------------
Java中使用RabbitMQ传递对象
参考文章:
https://blog.51cto.com/u_15060547/4382954
二:LocalDateTime的序列化
1:引入Maven文件
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
需要在LocalDateTime实例属性中添加下面的注解
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
后续更新中…