https://blog.csdn.net/m0_37867405/article/details/80793601

四、docker中使用rabbitmq

1. 搭建和启动

使用地址:rabbitmq docker

#1. 拉去rabbitmq的镜像
docker pull hub.c.163.com/library/rabbitmq:3.6.11-management
#2. 由于rabbitmq远程访问是不允许guest的,所以启动时候需要设置一个用户名和密码
docker run -d --hostname my-rabbit --name some-rabbit -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin -p 15672:15672 -p 5672:5672 hub.c.163.com/library/rabbitmq:3.6.11-management
# 提示信息:d525b1c1004f50284ca5bab76e8e5e2fea55462b72d9f923cea0da1a29e9aa9dnetstat
  • 1
  • 2
  • 3
  • 4
  • 5

在浏览器中访问:192.168.186.135:15672然后输入用户名和密码

2. java Hello world

简单的一对一生产消息

官网地址示例

1.引入 pom.xml

<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.0.0</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2.消息提供者

package com.itcloud.concurrency.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory; public class MessageProvider { private static final String HOST = "192.168.186.135"; private static final int PORT = 5672; // rabbitmq端口是5672 private static final String USERNAME = "admin"; private static final String PASSWORD = "admin"; private static final String QUEUE_NAME = "hello"; public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST);
factory.setPort(PORT);
factory.setUsername(USERNAME);
factory.setPassword(PASSWORD); Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "hello world";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" 生产消息:'" + message + "'"); } }

3.消费端

package com.itcloud.concurrency.rabbitmq;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP.BasicProperties; public class MessageConsumer { private static final String HOST = "192.168.186.135"; private static final int PORT = 5672; // rabbitmq端口是5672 private static final String USERNAME = "admin"; private static final String PASSWORD = "admin"; private static final String QUEUE_NAME = "hello"; public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(HOST);
factory.setPort(PORT);
factory.setUsername(USERNAME);
factory.setPassword(PASSWORD); Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
Consumer consumer = new DefaultConsumer(channel) { @Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println("消费端接收消息:" + message);
} };
//true 异步接收消息
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}

4.先后启动生产者和消费者

3. 一对多

官网示例

4. SpringBoot整合RabbitMQ

第一种交换模式:Direct

1.引入依赖

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

application.yml

spring:
rabbitmq:
host: 192.168.186.135
port: 5672
username: admin
password: admin

2.配置org.springframework.amqp.core.Queue

​ 【MQConfig.java】

@Configuration
public class MQConfig { public static final String QUEUE = "queue"; @Bean
public Queue queue() {
return new Queue(QUEUE);
} }
  1. 【MQSender.java】消息发送端
@Component
@Slf4j
public class MQSender { @Autowired
private AmqpTemplate amqpTemplate; public void sendMsg(String msg) {
log.info("发送消息:" + msg);
amqpTemplate.convertAndSend(MQConfig.QUEUE, msg);
} }

4.【MQReceiver.java】消息接收端

@Component
@Slf4j
public class MQReceiver { //绑定队列名称
@RabbitListener(queues = { MQConfig.QUEUE })
public void receive(String message) {
log.info("springboot rabbitmq recevie message:" + message);
}

5.简单的controller测试

    @PostMapping("/send")
public String sendMsg(String msg) {
mqSender.sendMsg(msg);
return "success";
}

第二种交换模式:Topic

:biking_woman:特点:

:ballot_box_with_check: 可以根据routing_key自由的绑定不同的队列

:ballot_box_with_check:发送端不需要知道发送到哪个队列,由routing_key去分发到队列中

2.配置org.springframework.amqp.core.Queue

​ 【MQConfig.java】

    public static final String TOPIC_EXCHANGE = "topic_exchange";

    public static final String QUEUE_HELLO = "topic_hello";

    public static final String QUEUE_WORLD = "topic_world";

    public static final String ROUT_HELLO = "hello_key";
public static final String ROUT_WORLD = "world_key";
...
//=============定义两个队列========================
@Bean
public Queue queueHello() {
return new Queue(QUEUE_HELLO);
} @Bean
public Queue queueWorld() {
return new Queue(QUEUE_WORLD);
}
//===================声明topinc交换模式=========================
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(TOPIC_EXCHANGE); }
//队列绑定到交换模式上
@Bean
@Autowired
public Binding bindingHello(Queue queueHello, TopicExchange topicExchange) {
return BindingBuilder.bind(queueHello).to(topicExchange).with(ROUT_HELLO);
} @Bean
@Autowired
public Binding bindingWorld(Queue queueWorld, TopicExchange topicExchange) {
return BindingBuilder.bind(queueWorld).to(topicExchange).with(ROUT_WORLD);
}
  1. 【MQSender.java】消息发送端
    public void sendHello(String msg) {
log.info("hello topic send messsgae:" + msg);
amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE, MQConfig.ROUT_HELLO, msg);
} public void sendWorld(String msg) {
log.info("world topic send messsgae:" + msg);
amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE, MQConfig.ROUT_WORLD, msg);
}

4.【MQReceiver.java】消息接收端

    @RabbitListener(queues = MQConfig.QUEUE_HELLO)
public void receiveHello(String msg) {
log.info("springboot rabbitmq recevie message topicHello:" + msg);
} @RabbitListener(queues = MQConfig.QUEUE_WORLD)
public void receiveWorld(String msg) {
log.info("springboot rabbitmq recevie message topicWorld:" + msg);
}

5.简单的controller测试

    @PostMapping("/send/topic/hello")
public String sendHello(String msg) {
mqSender.sendHello(msg);
return "success";
} @PostMapping("/send/topic/world")
public String sendWorld(String msg) {
mqSender.sendWorld(msg);
return "success";
}

第三种交换:Fanout

:biking_woman: 特点:只要绑定该交换机的消费者都可以接受到消息

1.配置org.springframework.amqp.core.Queue

​ 【MQConfig.java】

    public static final String FANOUT_EXCHANGE = "fanout_exchange";
public static final String QUEUE_FANOUT = "queue_fanout";
public static final String QUEUE_FANOUT2 = "queue_fanout2";
....
@Bean
public FanoutExchange fanoutExchange() {
return new FanoutExchange(FANOUT_EXCHANGE);
} @Bean
public Queue queueFanout() {
return new Queue(QUEUE_FANOUT);
} @Bean
public Queue queueFanout2() {
return new Queue(QUEUE_FANOUT2);
} @Bean
@Autowired
public Binding bindingFanout(FanoutExchange fanoutExchange, Queue queueFanout) {
return BindingBuilder.bind(queueFanout).to(fanoutExchange);
} @Bean
@Autowired
public Binding bindingFanout2(FanoutExchange fanoutExchange, Queue queueFanout2) {
return BindingBuilder.bind(queueFanout2).to(fanoutExchange);
}

2.【MQSender.java】消息发送端

    public void sendFanout(String msg) {
log.info("fanout send messsgae:" + msg);
amqpTemplate.convertAndSend(MQConfig.FANOUT_EXCHANGE, "", msg);
amqpTemplate.convertAndSend(MQConfig.FANOUT_EXCHANGE, "", "自定义消息");
}

3.【MQReceiver.java】消息接收端

    @RabbitListener(queues = MQConfig.QUEUE_FANOUT)
public void receiveFanout(String msg) {
log.info("springboot rabbitmq recevie message fanout:" + msg);
} @RabbitListener(queues = MQConfig.QUEUE_FANOUT2)
public void receiveFanout2(String msg) {
log.info("springboot rabbitmq recevie message fanout2:" + msg);
}

第四种交换模式:Headers

1.【MQConfig.java】

//======================headers交换模式============================

    public static final String HEADERS_EXCHANGE = "headers_exchange";

    public static final String QUEUE_HEADERS = "queue_headers";

    @Bean
public HeadersExchange headersExchange() {
return new HeadersExchange(HEADERS_EXCHANGE);
} @Bean
public Queue headersQueue() {
return new Queue(QUEUE_HEADERS, true);
} @Bean
@Autowired
public Binding headersBind(HeadersExchange headersExchange, Queue headersQueue ) {
Map<String, Object> headers = new HashMap<>();
headers.put("key1", "value1");
headers.put("key2", "value2");
return BindingBuilder.bind(headersQueue).to(headersExchange).whereAny(headers).match();

2.【MQSender.java】消息发送端

    public void sendHeaders(String msg) {
log.info("headers send messsgae:" + msg);
MessageProperties messageProperties = new MessageProperties();
messageProperties.setHeader("key1", "value1");
messageProperties.setHeader("key3", "value2");
Message message = new Message(msg.getBytes(), messageProperties);
amqpTemplate.convertAndSend(MQConfig.HEADERS_EXCHANGE, "", message);
}

3.【MQReceiver.java】消息接收端

    @RabbitListener(queues = MQConfig.QUEUE_HEADERS)
public void receiveHeaders(byte [] bytes) {
log.info("springboot rabbitmq recevie message headers:" + new String(bytes));
}

参考博客:

博客1 博客2

6. SpringCloud Stream

1. 创建生产者和消费者

1. 消息生产者:

新建【stream】springcloud项目

pom.xml

​ 其他依赖略

        <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
//注意导包
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel; //消息发送端接口
public interface SendMsg { public void send(Object obj); } //接口实现类
@EnableBinding(Source.class)
public class SendMsgImpl implements SendMsg { @Autowired
private MessageChannel output; @Override
public void send(Object obj) {
this.output.send(MessageBuilder.withPayload(obj).build());
} }

【application.yml】文件

server:
port: 8083
spring:
cloud:
stream:
binders:
defaultRabbit:
type: rabbit
environment: #配置rabbimq连接环境
spring:
rabbitmq:
host: 192.168.186.135
username: admin
password: admin
virtual-host: /
bindings:
output:
destination: myExchange #exchange名称,交换模式默认是topic
content-type: application/json
binder: defaultRabbit
//测试使用的Controller
@RestController
public class SendController { @Autowired
private SendMsg sendMsg; @GetMapping("/send")
public String msgSend(String msg) {
this.sendMsg.send(msg);
return "success";
}
}

2 .消息消费者

新建**【input】**springlcloud项目

//接口
public interface ReceiveMsg { public void receive(Message<Object> message); }
//实现类
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component; @Component
@EnableBinding(Sink.class)
public class ReceiveMsgImpl implements ReceiveMsg { @Override
@StreamListener(Sink.INPUT)
public void receive(Message<Object> message) {
System.out.println("接收消息" + message.getPayload());
}
}

application.yml

server:
port: 8085 spring:
cloud:
stream:
binders:
defaultRabbit:
type: rabbit
environment:
spring:
rabbitmq:
host: 192.168.186.135
username: admin
password: admin
virtual-host: /
bindings:
input:
destination: myExchange
content-type: application/json
binder: defaultRabbit

Rabbitmq基本使用 SpringBoot整合Rabbit SpringCloud Stream+Rabbit的更多相关文章

  1. 阶段5 3.微服务项目【学成在线】_day05 消息中间件RabbitMQ_17.RabbitMQ研究-与springboot整合-消费者代码

    创建消费者的类 使用@Component把这个类标记成一个Bean 把生产者里面创建的配置文件类复制过来 在原始的消费的方法上面 ,我们是可以拿到channel通道的 message.getBody就 ...

  2. 阶段5 3.微服务项目【学成在线】_day05 消息中间件RabbitMQ_14.RabbitMQ研究-与springboot整合-搭建环境

    我们选择基于Spring-Rabbit去操作RabbitMQ https://github.com/spring-projects/spring-amqp 使用spring-boot-starter- ...

  3. 阶段5 3.微服务项目【学成在线】_day05 消息中间件RabbitMQ_16.RabbitMQ研究-与springboot整合-生产者代码

    springBoot给我们提供了 RarbbitTemplate发送消息 创建测试类,因为我们是基于SpringBoot的来写的测试类.所以要加上@SpringBootTest和@RunWith的注解 ...

  4. 阶段5 3.微服务项目【学成在线】_day05 消息中间件RabbitMQ_15.RabbitMQ研究-与springboot整合-声明交换机和队列

    复制topic的代码 把常量都设置成public方便其他的类引用 ExchangeBuilder里面有4个方法分别对应四个交换机. 声明Email和短信的队列 队列绑定交换机 所以需要把Bean注入到 ...

  5. Java之RabbitMQ(一)与SpringBoot整合

    应用场景:异步处理.应用解耦.流量削峰 参照:https://blog.csdn.net/weixin_38364973/article/details/82834348 开端 RabbitAutoC ...

  6. SpringBoot28 RabbitMQ知识点、Docker下载RabbitMQ、SpringBoot整合RabbtiMQ

    1 RabbitMQ知识点 1.1 整体架构图 消息生产者将消息投递到exchange中,exchange会以某种路由机制将生产者投递的消息路由到queue中,消息消费者再从queue中获取消息进行消 ...

  7. RabbitMQ与SpringBoot整合

    RabbitMQ  SpringBoot  一.RabbitMQ的介绍 二.Direct模式 三.Topic转发模式 四.Fanout Exchange形式 原文地址: https://www.cnb ...

  8. springboot学习笔记-6 springboot整合RabbitMQ

    一 RabbitMQ的介绍 RabbitMQ是消息中间件的一种,消息中间件即分布式系统中完成消息的发送和接收的基础软件.这些软件有很多,包括ActiveMQ(apache公司的),RocketMQ(阿 ...

  9. SpringBoot系列八:SpringBoot整合消息服务(SpringBoot 整合 ActiveMQ、SpringBoot 整合 RabbitMQ、SpringBoot 整合 Kafka)

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合消息服务 2.具体内容 对于异步消息组件在实际的应用之中会有两类: · JMS:代表作就是 ...

随机推荐

  1. C++11之for循环的新用法《转》

    相关资料:https://legacy.gitbook.com/book/changkun/cpp1x-tutorial/details C++11之for循环的新用法 C++使用如下方法遍历一个容器 ...

  2. SQL之to_date()以及关于日期处理的详解

    日期例子: SELECT TO_DATE('2006-05-01 19:25:34', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL SELECT TO_DATE('2006- ...

  3. iOS响应链原理

    ios找到被点击的view的过程是从根view开始递归地调用hitTest方法,直到有一个子view的hitTest方法返回自身:如果所有一级子view的hitTest方法都返回nil,那么根view ...

  4. 为什么java实体类需要重写toString方法

    如果没重写toString的情况: Object 类的 toString 方法 返回一个字符串,该字符串由类名(对象是该类的一个实例).at 标记符“@”和此对象哈希码的无符号十六进制表示组成.换句话 ...

  5. 关于maven中的快照版本(snapshot)与正式版本(release)解析。

    Maven中建立的依赖管理方式基本已成为Java语言依赖管理的事实标准,Maven的替代者Gradle也基本沿用了Maven的依赖管理机制.在Maven依赖管理中,唯一标识一个依赖项是由该依赖项的三个 ...

  6. 观察者模式——Head First

    一.定义 观察者模式(Observer Pattern)定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新. 二.类图 三.气象站 //Subject p ...

  7. Haskell语言学习笔记(80)req

    req req 是一个好用,类型安全,可扩展,上层的HTTP客户端的库. $ cabal install req Installed req-1.1.0 Prelude> :m +Network ...

  8. IPSec协议;IPv6为何增加对IPSec协议的支持

      IPSec由一系列的协议组成,除IP层的协议完全结构外,还包括了AH.ESP.ISAKMP.ISAKMP的因特网IP安全解释域.IKE.OAKLEY密钥协议确定等.ESP和AH定义协议.载荷头的格 ...

  9. ArcGIS案例学习笔记3_1_地理配准案例_目视找点

    ArcGIS案例学习笔记3_1_地理配准案例_目视找点 计划时间:第3天上午 方法:地理配准/添加链接点/左键/右键/输入坐标 数据:江苏省.zip 矢量:省界,市界,GPS WGS84 地理坐标系 ...

  10. ArcGIS案例学习笔记-批量裁剪地理模型

    ArcGIS案例学习笔记-批量裁剪地理模型 联系方式:谢老师,135-4855-4328,xiexiaokui#qq.com 功能:空间数据的批量裁剪 优点:1.批量裁剪:任意多个目标数据,去裁剪任意 ...