RabbitMQ代码操作之发消息和序列化机制

几个自动配置类:文章来源地址https://www.yii666.com/article/754385.html文章地址https://www.yii666.com/article/754385.html网址:yii666.com<网址:yii666.com

1.RabbitAutoConfiguration
2.有自动配置了连接工厂 ConnectionFactory
3.RabbitProperties 封装了RabbitMQ的配置
4.RabiitTemlate:给RabbitMQ发送和接收消息
5.AmqpAdmin:RabbitMQ系统管理功能组件(可以创建exchange,queue,Binding)
6.@EnableRabbit+@RabbitListener 监听消息队列的内容文章来源地址:https://www.yii666.com/article/754385.html

  • 配置文件写法:
spring.rabbitmq.host=192.168.0.113
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
#端口5672默认可以不写
#spring.rabbitmq.virtual-host= 默认/可以不写
  • 测试类:
@SpringBootTest
public class Springboot002AmqpApplicationTests { @Autowired
RabbitTemplate rabbitTemplate; /*
1.单播(点对点)
public Message(byte[] body, MessageProperties messageProperties) {
this.body = body;
this.messageProperties = messageProperties;
}
* */
@Test
public void contextLoads() {
//交换器,路邮件,消息
//Message需要自己构造一个,定一消息体内容和消息头
//rabbitTemplate.send(exchange,routekey,message); //转法并发送,Object默认当成消息体,只需要传入要发送的对象,自动序列化保存发送给rabbitmq
//rabbitTemplate.convertAndSend(exchange,routKey,object);
Map <String ,Object>map = new HashMap<>();
map.put("msg","这是第一个消息");
map.put("data", Arrays.asList("helloWorld","123",true));
//对象被默认序列化后发送出去
//rabbitTemplate.convertAndSend("exchange.direct","springbootTest.news",map);
//json发送MyAMQPConfig类配置
rabbitTemplate.convertAndSend("exchange.direct","springbootTest.news",new Book("西游记","吴承恩"));
} //接收
@Test
public void receive(){
Object o = rabbitTemplate.receiveAndConvert("springbootTest.news");
//打印数据类型
System.out.println(o.getClass());
System.out.println(o);
}
/*
* 1.单播
* */
@Test
public void setOneMsg(){
rabbitTemplate.convertAndSend("exchange.direct","springbootTest",new Book("水浒传","单播")); /*
* 2.广播
* */
@Test
public void setAllMsg(){
rabbitTemplate.convertAndSend("exchange.fanout","",new Book("红楼梦","曹雪芹")); }
发送消息时如不配置序列化方法则按照java默认序列化机制,则会造成发送编码不符合
解决方法:
json发送MyAMQPConfig类配置
@Configuration
public class MyAMQPConfig {
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}

版权声明:本文内容来源于网络,版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。文本页已经标记具体来源原文地址,请点击原文查看来源网址,站内文章以及资源内容站长不承诺其正确性,如侵犯了您的权益,请联系站长如有侵权请联系站长,将立刻删除

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信图片_20190322181744_03.jpg

微信扫一扫打赏

请作者喝杯咖啡吧~

支付宝扫一扫领取红包,优惠每天领

二维码1

zhifubaohongbao.png

二维码2

zhifubaohongbao2.png