作者:Tom哥
公众号:微观技术
博客:https://offercome.cn
人生理念:知道的越多,不知道的越多,努力去学
Spring Boot 作为主流微服务框架,拥有成熟的社区生态。市场应用广泛,为了方便大家,整理了一个基于spring boot的常用中间件快速集成入门系列手册,涉及RPC、缓存、消息队列、分库分表、注册中心、分布式配置等常用开源组件,大概有几十篇文章,陆续会开放出来,感兴趣同学可以关注&收藏
RabbitMQ 是使用 Erlang 语言来编写的,并且 RabbitMQ 是基于 AMQP 协议的。Erlang语言在数据交互方面性能优秀,有着和原生Socket一样的延迟,这也是RabbitMQ高性能的原因所在。
提到RabbitMQ,就不得不提AMQP协议。AMQP协议是二进制协议。是一个提供统一消息服务的应用层标准高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计。
在 pom.xml 文件中添加 RabbitMQ 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
在配置文件 application.yaml 中配置 RabbitMQ 的相关参数,具体内容如下:
spring:
application:
name: spring-boot-bulking-rabbitmq
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
@Configuration
public class RabbitMQConfig {
@Getter
public static String NEW_USER_TOPIC = "new-user";
/**
* 自动创建队列
*/
@Bean
public Queue createQueue() {
return new Queue(NEW_USER_TOPIC, true);
}
}
Long id = Long.valueOf(new Random().nextInt(1000));
User user = User.builder().id(id).userName("TomGE").age(29).address("上海").build();
byte[] useByte = JSON.toJSONString(user).getBytes(StandardCharsets.UTF_8);
// 指定消息类型
MessageProperties props = MessagePropertiesBuilder.newInstance()
.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN).build();
rabbitTemplate.send(RabbitMQConfig.NEW_USER_TOPIC, new Message(useByte, props));
@RabbitListener(queues = "new-user")
public void onMessage(Message message, Channel channel) throws Exception {
String s = new String(message.getBody(), StandardCharsets.UTF_8);
System.out.println("消费内容 : " + s);
// 提交消息ack
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
}
控制台地址:
http://localhost:15672/#/queues
https://github.com/aalansehaiyang/spring-boot-bulking
模块:spring-boot-bulking-rabbitmq