博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot项目中集成RabbitMQ
阅读量:3947 次
发布时间:2019-05-24

本文共 2056 字,大约阅读时间需要 6 分钟。

  前面有几篇文章对RabbitMQ基本原理做了介绍,此篇文章记录一下RabbitMQ在Springboot项目中简单的集成使用。

1.创建springboot项目,引入rabbitmq和web依赖

在这里插入图片描述

  1. 引入rabbitmq依赖之后,springboot会自动配置rabbitmq,可以从RabbitAutoConfiguration类中查看自动配置情况:

    2.1 其中有rabbitmq的连接工厂类

在这里插入图片描述

2.2 另外还有一个比较重要的RabbitTemplatebean对象,此对象是用来操作rabbitmq进行发送接收消息的模板,作用类似于redis中的redisTemplate

在这里插入图片描述
2.3 从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源码中由于我们现在自己指定了messageConverterJackson2JsonMessageConverter,所以现在的消息序列化方式就是json形式。

在这里插入图片描述

此时我们再次发送一个Book对象的消息,从web控制面板中可以看出,自定义json序列化方式配置成功:
在这里插入图片描述

当我们获取消息的时候:

在这里插入图片描述

转载地址:http://sphwi.baihongyu.com/

你可能感兴趣的文章
创新服务的七要素
查看>>
虚伪的奉承也有效
查看>>
蒂姆·库克的五项核心领导力
查看>>
你为何没有成为领导者
查看>>
一切悲剧都源于不当激励
查看>>
别把用户的高期望混同于好体验
查看>>
动机和机会:推动商业发展的引擎
查看>>
4个信号表明你是一个失败的领导
查看>>
成功谈判 你需要几个锦囊?
查看>>
一个人的宽度决定了他的高度
查看>>
善于拜访是另一种经营智慧
查看>>
打造新老员工双赢机制变对立为统一
查看>>
企业如何避免用错人
查看>>
打掉苹果“无与伦比”的傲慢(人民时评)
查看>>
Creating an Android Project
查看>>
Running Your App (android)
查看>>
Starting Another Activity
查看>>
Starting an Activity
查看>>
Stopping and Restarting an Activity
查看>>
Using the Support Library
查看>>