RabbitMQ(6)使用RabbitMQ发送-接收对象.md
- 本周就是将对象转换成字符串进行传递
1.对象序列化实现
- bean实现序列化接口
- 生产者消费者的bean包名必须一致
消息生产者
1
2
3
4
5
6
7
8
9
10
11
public class SendMsgService {
private AmqpTemplate amqpTemplate;
public void sendMsg(Goods goods) {
byte[] bytes = SerializationUtils.serialize(goods);
amqpTemplate.convertAndSend("queue1",bytes);
}
}消息消费者
1
2
3
4
5
6
7
8
9
10
11
public class ReviceMsgService {
public void receiveMsg(byte[] bs) {
Goods goods = (Goods) SerializationUtils.deserialize(bs);
System.out.println(goods);
}
}
2.JSON字符串实现
消息生产者
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SendMsgService {
private AmqpTemplate amqpTemplate;
public void sendMsg(Goods goods) throws JsonProcessingException {
ObjectMapper mapper=new ObjectMapper();
String message=mapper.writeValueAsString(goods);
amqpTemplate.convertAndSend("queue1",message);
}
}消息消费者
1
2
3
4
5
6
7
8
9
10
11
12
public class ReviceMsgService {
public void receiveMsg(String msg) throws JsonProcessingException {
ObjectMapper mapper=new ObjectMapper();
Goods goods=mapper.readValue(msg,Goods.class);
System.out.println(goods);
}
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LT的编程笔记!