原文:https://www.jianshu.com/p/e1258c004314

RabbitMQ作为AMQP的代表性产品,在项目中大量使用。结合现在主流的spring boot,极大简化了开发过程中所涉及到的消息通信问题。

首先正确的安装RabbitMQ及运行正常。

RabbitMQ需啊erlang环境,所以首先安装对应版本的erlang,可在RabbitMQ官网下载

# rpm -ivh erlang-19.0.4-1.el7.centos.x86_64.rpm

使用yum安装RabbitMQ,避免缺少依赖包引起的安装失败

# yum install rabbitmq-server-3.6.6-1.el7.noarch.rpm

启动RabbitMQ

# /sbin/service rabbitmq-server start

由于RabbitMQ默认提供的guest用户只能本地访问,所以额外创建用户用于测试

# /sbin/rabbitmqctl add_user test test123
用户名:test,密码:test123

开启web管理插件

# rabbitmq-plugins enable rabbitmq_management

并使用之前创建的用户登录,并设置该用户为administrator,虚拟主机地址为/

spring boot 引入相关依赖

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>

消息生产者

application.properties添加一下配置
spring.rabbitmq.host=192.168.1.107
spring.rabbitmq.port=5672
spring.rabbitmq.username=test
spring.rabbitmq.password=test123
spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.publisher-returns=true
spring.rabbitmq.template.mandatory=true
spring boot配置类,作用为指定队列,交换器类型及绑定操作
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class RabbitConfig { //声明队列
@Bean
public Queue queue1() {
return new Queue("hello.queue1", true); // true表示持久化该队列
} @Bean
public Queue queue2() {
return new Queue("hello.queue2", true);
} //声明交互器
@Bean
TopicExchange topicExchange() {
return new TopicExchange("topicExchange");
} //绑定
@Bean
public Binding binding1() {
return BindingBuilder.bind(queue1()).to(topicExchange()).with("key.1");
} @Bean
public Binding binding2() {
return BindingBuilder.bind(queue2()).to(topicExchange()).with("key.#");
} }

共声明了2个队列,分别是hello.queue1,hello.queue2,交换器类型为TopicExchange,并与hello.queue1,hello.queue2队列分别绑定。

生产者类
import java.util.UUID;

import javax.annotation.PostConstruct;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; @Component
public class Sender implements RabbitTemplate.ConfirmCallback, ReturnCallback { @Autowired
private RabbitTemplate rabbitTemplate; @PostConstruct
public void init() {
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.setReturnCallback(this);
} @Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
if (ack) {
System.out.println("消息发送成功:" + correlationData);
} else {
System.out.println("消息发送失败:" + cause);
} } @Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
System.out.println(message.getMessageProperties().getCorrelationIdString() + " 发送失败"); } //发送消息,不需要实现任何接口,供外部调用。
public void send(String msg){ CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString()); System.out.println("开始发送消息 : " + msg.toLowerCase());
String response = rabbitTemplate.convertSendAndReceive("topicExchange", "key.1", msg, correlationId).toString();
System.out.println("结束发送消息 : " + msg.toLowerCase());
System.out.println("消费者响应 : " + response + " 消息处理完成");
}
}

要点:

1.注入RabbitTemplate

2.实现RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback接口(非必须)。
ConfirmCallback接口用于实现消息发送到RabbitMQ交换器后接收ack回调。ReturnCallback接口用于实现消息发送到RabbitMQ交换器,但无相应队列与交换器绑定时的回调。

3.实现消息发送方法。调用rabbitTemplate相应的方法即可。rabbitTemplate常用发送方法有

rabbitTemplate.send(message);   //发消息,参数类型为org.springframework.amqp.core.Message
rabbitTemplate.convertAndSend(object); //转换并发送消息。 将参数对象转换为org.springframework.amqp.core.Message后发送
rabbitTemplate.convertSendAndReceive(message) //转换并发送消息,且等待消息者返回响应消息。

针对业务场景选择合适的消息发送方式即可。

消息消费者
application.properties添加一下配置
spring.rabbitmq.host=192.168.1.107
spring.rabbitmq.port=5672
spring.rabbitmq.username=test
spring.rabbitmq.password=test123 spring.rabbitmq.listener.concurrency=2 //最小消息监听线程数
spring.rabbitmq.listener.max-concurrency=2 //最大消息监听线程数
消费者类
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component; @Component
public class Receiver { @RabbitListener(queues = "hello.queue1")
public String processMessage1(String msg) {
System.out.println(Thread.currentThread().getName() + " 接收到来自hello.queue1队列的消息:" + msg);
return msg.toUpperCase();
} @RabbitListener(queues = "hello.queue2")
public void processMessage2(String msg) {
System.out.println(Thread.currentThread().getName() + " 接收到来自hello.queue2队列的消息:" + msg);
}
}

由于定义了2个队列,所以分别定义不同的监听器监听不同的队列。由于最小消息监听线程数和最大消息监听线程数都是2,所以每个监听器各有2个线程实现监听功能。

要点:

1.监听器参数类型与消息实际类型匹配。在生产者中发送的消息实际类型是String,所以这里监听器参数类型也是String。

2.如果监听器需要有响应返回给生产者,直接在监听方法中return即可。

运行测试

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.sam.demo.rabbitmq.Application;
import com.sam.demo.rabbitmq.sender.Sender; @RunWith(value=SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class RabbitTests { @Autowired
private Sender sender; @Test
public void sendTest() throws Exception {
while(true){
String msg = new Date().toString();
sender.send(msg);
Thread.sleep(1000);
}
}
}

输出:

开始发送消息 : wed mar 29 23:20:52 cst 2017
SimpleAsyncTaskExecutor-1 接收到来自hello.queue2队列的消息:Wed Mar 29 23:20:52 CST 2017
SimpleAsyncTaskExecutor-2 接收到来自hello.queue1队列的消息:Wed Mar 29 23:20:52 CST 2017
结束发送消息 : wed mar 29 23:20:52 cst 2017
消费者响应 : WED MAR 29 23:20:52 CST 2017 消息处理完成
------------------------------------------------
消息发送成功:CorrelationData [id=340d14e6-cfcc-4653-9f95-29b37d50f886]
开始发送消息 : wed mar 29 23:20:53 cst 2017
SimpleAsyncTaskExecutor-1 接收到来自hello.queue1队列的消息:Wed Mar 29 23:20:53 CST 2017
SimpleAsyncTaskExecutor-2 接收到来自hello.queue2队列的消息:Wed Mar 29 23:20:53 CST 2017
结束发送消息 : wed mar 29 23:20:53 cst 2017
消费者响应 : WED MAR 29 23:20:53 CST 2017 消息处理完成
------------------------------------------------
消息发送成功:CorrelationData [id=e4e01f89-d0d4-405e-80f0-85bb20238f34]
开始发送消息 : wed mar 29 23:20:54 cst 2017
SimpleAsyncTaskExecutor-2 接收到来自hello.queue1队列的消息:Wed Mar 29 23:20:54 CST 2017
SimpleAsyncTaskExecutor-1 接收到来自hello.queue2队列的消息:Wed Mar 29 23:20:54 CST 2017
结束发送消息 : wed mar 29 23:20:54 cst 2017
消费者响应 : WED MAR 29 23:20:54 CST 2017 消息处理完成
------------------------------------------------

如果需要使用的其他的交换器类型,spring中都已提供实现,所有的交换器均实现org.springframework.amqp.core.AbstractExchange接口。

常用交换器类型如下:

Direct(DirectExchange):direct 类型的行为是"先匹配, 再投送". 即在绑定时设定一个 routing_key, 消息的routing_key完全匹配时, 才会被交换器投送到绑定的队列中去。

Topic(TopicExchange):按规则转发消息(最灵活)。

Headers(HeadersExchange):设置header attribute参数类型的交换机。

Fanout(FanoutExchange):转发消息到所有绑定队列。

作者:SamHxm
链接:https://www.jianshu.com/p/e1258c004314
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

spring boot集成RabbitMQ的更多相关文章

  1. Spring Boot 集成 RabbitMQ 实战

    Spring Boot 集成 RabbitMQ 实战 特别说明: 本文主要参考了程序员 DD 的博客文章<Spring Boot中使用RabbitMQ>,在此向原作者表示感谢. Mac 上 ...

  2. Spring boot集成RabbitMQ(山东数漫江湖)

    RabbitMQ简介 RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统 MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法.应用程序通过读写出 ...

  3. 85. Spring Boot集成RabbitMQ【从零开始学Spring Boot】

    这一节我们介绍下Spring Boot整合RabbitMQ,对于RabbitMQ这里不过多的介绍,大家可以参考网络上的资源进行安装配置,本节重点是告诉大家如何在Spring Boot中使用Rabbit ...

  4. RabbitMQ(3) Spring boot集成RabbitMQ

    springboot集成RabbitMQ非常简单,如果只是简单的使用配置非常少,springboot提供了spring-boot-starter-amqp项目对消息各种支持. 资源代码:练习用的代码. ...

  5. Spring Boot 集成RabbitMQ

    在Spring Boot中整合RabbitMQ是非常容易的,通过在Spring Boot应用中整合RabbitMQ,实现一个简单的发送.接收消息的例子. 首先需要启动RabbitMQ服务,并且add一 ...

  6. spring boot 集成 rabbitmq 指南

    先决条件 rabbitmq server 安装参考 一个添加了 web 依赖的 spring boot 项目 我的版本是 2.5.2 添加 maven 依赖 <dependency> &l ...

  7. spring boot 集成 rabbitmq

    1.使用默认的AmqpTemplate生产消费pojo时,pojo需要implement Serializable,否则会抛出org.springframework.amqp.AmqpExceptio ...

  8. spring boot 集成RabbitMQ的异常

    com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.clos ...

  9. Spring boot集成Rabbit MQ使用初体验

    Spring boot集成Rabbit MQ使用初体验 1.rabbit mq基本特性 首先介绍一下rabbitMQ的几个特性 Asynchronous Messaging Supports mult ...

随机推荐

  1. SQL行列转换的另一种方法

    create table tb(姓名 varchar(10) , 课程 varchar(10) , 分数 int)insert into tb values('张三' , '语文' , 74)inse ...

  2. 【TensorFlow】一文弄懂CNN中的padding参数

    在深度学习的图像识别领域中,我们经常使用卷积神经网络CNN来对图像进行特征提取,当我们使用TensorFlow搭建自己的CNN时,一般会使用TensorFlow中的卷积函数和池化函数来对图像进行卷积和 ...

  3. CVE-2012-0003 Microsoft Windows Media Player ‘winmm.dll’ MIDI文件解析远程代码执行漏洞 分析

    [CNNVD]Microsoft Windows Media Player ‘winmm.dll’ MIDI文件解析远程代码执行漏洞(CNNVD-201201-110)    Microsoft Wi ...

  4. 浅谈malloc/free和new/delete 的区别

    malloc和new的区别 malloc是库函数,需要包头文件才能成功运行编译:new是操作符(C++中的关键字),需要在C++的环境下使用. malloc既可以在C语言中使用也可以在C++中使用,n ...

  5. git/github 生成密钥

    当从本地提交文件到github的时候,提交不成功,报错,可能问题就是你还没有生成ssh秘钥 github要使用ssh密钥的原因: git使用https协议,每次pull, push都要输入密码,相当的 ...

  6. RabbitMQ介绍及安装部署

    本节内容: RabbitMQ介绍 RabbitMQ运行原理 RabbitMQ重要术语 三种ExchangeType RabbitMQ集群种类 集群基本概念 镜像模式部署集群 一.RabbitMQ介绍 ...

  7. GridView练习题

    package com.example.wang.myapplication; import android.os.Bundle; import android.support.v7.app.AppC ...

  8. Java项目中classpath路径

    1.src不是classpath, WEB-INF/classes.lib.resources才是classpath,WEB-INF/是资源目录, 客户端不能直接访问. 2.WEB-INF/class ...

  9. 【51nod】1742 开心的小Q

    题解 我们由于莫比乌斯函数如果有平方数因子就是0,那么我们可以列出这样的式子 \(\sum_{i = 1}^{n} \sum_{d|i} (1 - |\mu(d)|)\) 然后枚举倍数 \(\sum_ ...

  10. 自定义排序及Hadoop序列化

    自定义排序 将两列数据进行排序,第一列按照升序排列,当第一列相同时,第二列升序排列. 在map和reduce阶段进行排序时,比较的是k2.v2是不参与排序比较的.如果要想让v2也进行排序,需要把k2和 ...