本文共 2056 字,大约阅读时间需要 6 分钟。
前面有几篇文章对RabbitMQ基本原理做了介绍,此篇文章记录一下RabbitMQ在Springboot项目中简单的集成使用。
1.创建springboot项目,引入rabbitmq和web依赖
引入rabbitmq
依赖之后,springboot会自动配置rabbitmq
,可以从RabbitAutoConfiguration
类中查看自动配置情况:
2.1 其中有rabbitmq的连接工厂类
2.2 另外还有一个比较重要的RabbitTemplate
bean对象,此对象是用来操作rabbitmq进行发送接收消息的模板,作用类似于redis中的redisTemplate
。
RabbitAutoConfiguration
自动配置类中可以看到还有RabbitProperties
也就是rabbitmq
的配置类,其中有对于rabbitmq
的默认配置信息。 3.在配置文件application.properties
中配置rabbitmq
spring.rabbitmq.host=47.93.181.229spring.rabbitmq.username=guestspring.rabbitmq.password=guest
4.使用RabbitTemplate
操作rabbitmq
发送接收消息
package org.magic.rabbitmq;import org.junit.jupiter.api.Test;import org.springframework.amqp.rabbit.core.RabbitTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestclass RabbitmqApplicationTests { private static final String EXCHANGE_DIRECT = "exchange.direct"; @Autowired private RabbitTemplate rabbitTemplate; /** * 发送String 类型的消息 */ @Test void sendMsg() { String msg = "这是项目中发送的一条测试消息~"; rabbitTemplate.convertAndSend(EXCHANGE_DIRECT, "javamagic.news", msg); } /** * 接收String类型的消息 */ @Test void getMsg() { Object o = rabbitTemplate.receiveAndConvert("javamagic.news"); System.out.println(o.getClass()); System.out.println(o); }}
5.如果想要发送的消息是一个对象类型的:
/** * 发送 对象 类型的消息 */ @Test void sendObjMsg() { rabbitTemplate.convertAndSend(EXCHANGE_DIRECT,"javamagic.news",new Book("三国演义","罗贯中")); }
如果发送到rabbitmq中,通过web控制面板可以看到rabbitmq将Book
对象进行序列化了:
因为rabbitmqTemplate
默认的消息转换器使用的就是jdk序列化规则:
private MessageConverter messageConverter = new SimpleMessageConverter();
而消息转换器的实现类型有很多种:
我们也可以选择使用json形式的消息转换器进行序列化,@Configurationpublic class ConverterConfig { @Bean public MessageConverter messageConverter() { return new Jackson2JsonMessageConverter(); }}
这里我们自己可以指定消息转换器使用json的方式进行序列化,rabbitmaTemplate
源码中由于我们现在自己指定了messageConverter
为Jackson2JsonMessageConverter
,所以现在的消息序列化方式就是json形式。
Book
对象的消息,从web控制面板中可以看出,自定义json序列化方式配置成功: 当我们获取消息的时候:
转载地址:http://sphwi.baihongyu.com/