消息中间件RabbitMQ 实例 (一)

消息中间件RabbitMQ

1 RabbitMQ简介

1.1消息队列中间件简介

消息队列中间件是分布式系统中重要的组件,主要解决应用耦合,异步消息,流量削锋等问题实现高性能,高可,可伸缩和最终一致性[架构] 使用较多的消息队列有:我接触过的也就这些了。
ActiveMQ,RabbitMQ,Kafka,RocketMQ

以下介绍消息队列在实际应用中常用的使用场景:异步处理,应用解耦,流量削锋和消息通讯四个场景

1.2什么是RabbitMQ

RabbitMQ 是一个由 Erlang 语言开发的 AMQP 的开源实现。
AMQP :Advanced Message Queue,高级消息队列协议。它是应用层协议的一个开放标准,为面向消息的中间件设计,基于此协议的客户端与消息中间件可传递消息,并不受产品、开发语言等条件的限制。
RabbitMQ 最初起源于金融系统,用于在分布式系统中存储转发消息,在易用性、扩展性、高可用性等方面表现不俗。具体特点包括:
1**.可靠性**(Reliability)RabbitMQ 使用一些机制来保证可靠性,如持久化、传输确认、发布确认。

2**.灵活的路由**(Flexible Routing)在消息进入队列之前,通过 Exchange 来路由消息的。对于典型的路由功能,RabbitMQ已经提供了一些内置的 Exchange 来实现。针对更复杂的路由功能,可以将多个Exchange 绑定在一起,也通过插件机制实现自己的 Exchange 。
3.消息集群(Clustering)多个 RabbitMQ 服务器可以组成一个集群,形成一个逻辑 Broker 。
4.高可用(Highly Available Queues)队列可以在集群中的机器上进行镜像,使得在部分节点出问题的情况下队列仍然可用。
5**.多种协议**(Multi-protocol)RabbitMQ 支持多种消息队列协议,比如 STOMP、MQTT 等等。
6.多语言客户端(Many Clients)RabbitMQ 几乎支持所有常用语言,比如 Java、.NET、Ruby 等等。
7.管理界面(Management UI)RabbitMQ 提供了一个易用的用户界面,使得用户可以监控和管理消息 Broker 的许多方面。
8.跟踪机制(Tracing)如果消息异常,RabbitMQ 提供了消息跟踪机制,使用者可以找出发生了什么。
9.插件机制(Plugin System)RabbitMQ 提供了许多插件,来从多方面进行扩展,也可以编写自己的插件。

1.3架构图与主要概念
1.3.1架构图

在这里插入图片描述

1.3.2主要概念

RabbitMQ Server: 也叫broker server,它是一种传输服务。 他的角色就是维护一条从Producer到Consumer的路线,保证数据能够按照指定的方式进行传输。

Producer: 消息生产者,如图A、B、C,数据的发送方。消息生产者连接RabbitMQ服务器然后将消息投递到Exchange。

Consumer:消息消费者,如图1、2、3,数据的接收方。消息消费者订阅队列,RabbitMQ将Queue中的消息发送到消息消费者。

Exchange:生产者将消息发送到Exchange(交换器),由Exchange将消息路由到一个或多个Queue中(或者丢弃)。Exchange并不存储消息。RabbitMQ中的Exchange有direct、fanout、topic、headers四种类型,每种类型对应不同的路由规则。

Queue:(队列)是RabbitMQ的内部对象,用于存储消息。消息消费者就是通过订阅队列来获取消息RabbitMQ中的消息都只能存储在Queue中,生产者生产消息并最终投递到Queue中,消费者可以从Queue中获取消息并消费。多个消费者可以订阅同一个Queue,这时Queue中的消息会被平均分摊给多个消费者进行处理,而不是每个消费者都收到所有的消息并处理。

RoutingKey:生产者在将消息发送给Exchange的时候,一般会指定一个routing key,来指定这个消息的路由规则,而这个routing key需要与Exchange Type及binding key联合使用才能最终生效。在Exchange Type与binding key固定的情况下(在正常使用时一般这些内容都是固定配置好的),我们的生产者就可以在发送消息给Exchange时,通过指定routing key来决定消息流向哪里。RabbitMQ为routing key设定的长度限制为255bytes。

Connection: (连接):Producer和Consumer都是通过TCP连接到RabbitMQ Server的。以后我们可以看到,程序的起始处就是建立这个TCP连接。

Channels: (信道):它建立在上述的TCP连接中。数据流动都是在Channel中进行的。也就是说,一般情况是程序起始建立TCP连接,第二步就是建立这个Channel。

VirtualHost:权限控制的基本单位,一个VirtualHost里面有若干Exchange和MessageQueue,以及指定被哪些user使用。

2 RabbitMQ

2.1 RabbitMQ安装与启动
2.1.1 windows下的安装

1)下载安装eralang

otp_win64_20.2.exe 或者更高版本https://www.erlang.org/downloads

2)下载安装rabbitmq https://www.rabbitmq.com/news.html#2019-07-08T09:00:00+00:00

我这里使用的是rabbitmq-server-3.7.4.exe

安装目录中不能有中文或者空格,如果有请重新安装

3)安装管理界面(插件)

进入rabbitMQ安装目录的sbin目录,输入命令

rabbitmq‐plugins enable rabbitmq_management



D:\rabbitmq\rabbitmq_server-3.7.4\sbin>rabbitmq-plugins enable rabbitmq_management
Enabling plugins on node rabbit@7DXOSPRVGV8O21O:
rabbitmq_management
The following plugins have been configured:
  rabbitmq_management
  rabbitmq_management_agent
  rabbitmq_web_dispatch
Applying plugin configuration to rabbit@7DXOSPRVGV8O21O...
Plugin configuration unchanged.

D:\rabbitmq\rabbitmq_server-3.7.4\sbin>

(4)重新启动服务

D:\rabbitmq\rabbitmq_server-3.7.4\sbin>rabbitmq-server

  ##  ##
  ##  ##      RabbitMQ 3.7.4. Copyright (C) 2007-2018 Pivotal Software, Inc.
  ##########  Licensed under the MPL.  See http://www.rabbitmq.com/
  ######  ##
  ##########  Logs: C:/Users/Administrator/AppData/Roaming/RabbitMQ/log/rabbit@7DXOSPRVGV8O21O.log
                    C:/Users/Administrator/AppData/Roaming/RabbitMQ/log/rabbit@7DXOSPRVGV8O21O_upgrade.log

              Starting broker...
 completed with 3 plugins.



(5)打开浏览器,地址栏输入http://127.0.0.1:15672 ,即可看到管理界面的登陆页

(6) 默认的用户名密码为guest guest

2.1.2 docker下的安装
[root@localhost ~]# docker run -di --name=liubijun_rabbitmq -p 5671:5617 -p 5672:5672 -p 4369:4369 -p 15671:15671 -p 15672:15672 -p 25672:25672 rabbitmq:management
WARNING: IPv4 forwarding is disabled. Networking will not work.
894c19980c8d3f0db669dfdacc0a3a154feaa512ea733a7d37df2f6df3b52c64
[root@localhost ~]# 

注意,如果docker 上次待机没有重启,会遇见很多未知问题,测试的时候,建议最好重启下,然后在启东容器正常工作。

2.2 直接模式
2.2.1 什么是Direct模式

我们需要将消息发送给唯一一个节点时候,使用这种模式,也是最简单的模式。

在这里插入图片描述

任何发送到Direct Exchange的消息都会被转发到RouteKey中指定的Queue。

1.一般情况可以使用rabbitMQ自带的Exchange:”"(该Exchange的名字为空字符串,下

文称其为default Exchange)。

2.这种模式下不需要将Exchange进行任何绑定(binding)操作

3.消息传递时需要一个“RouteKey”,可以简单的理解为要发送到的队列名字。

4.如果vhost中不存在RouteKey中指定的队列名,则该消息会被抛弃。

2.2.2 创建队列

在这里插入图片描述

Durability:是否做持久化 Durable(持久) transient(临时)
Auto delete : 是否自动删除

2.2.3 代码实现-消息生产者
2.2.3.1 导入依赖
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

2.2.3.2 配置文件

spring:
  rabbitmq:
    host: 192.168.85.198


2.2.3.3 生产者

package com.liu.test;

import com.liu.rabbitmq.RabbitMqApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Created by Administrator on 2019/8/20 0020.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RabbitMqApplication.class)
public class ProducerTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
   public void sendMsg() throws InterruptedException {
       for (int i = 0;i<10000;i++){
           //Thread.sleep(100);
           rabbitTemplate.convertAndSend("liubijun","rabbitmq hello world!"+i);
       }
   }
}

2.2.3.3 消费者
package rabbitmq.customer;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/8/20 0020.
 */
@Component
@RabbitListener(queues = "liubijun")
public class Customer1 {

    @RabbitHandler
    public void getMsg(String msg){
        System.out.println( "消费者1号,消费消息:"+msg);
    }

}

2.3 分列模式
2.3.1 什么是分列(Fanout)模式

在这里插入图片描述

任何发送到Fanout Exchange的消息都会被转发到与该Exchange绑定(Binding)的所有Queue上。

1.可以理解为路由表的模式

2.这种模式不需要RouteKey

3.这种模式需要提前将Exchange与Queue进行绑定,一个Exchange可以绑定多个Queue,一个Queue可以同多个Exchange进行绑定。

4.如果接受到消息的Exchange没有与任何Queue绑定,则消息会被抛弃。

2.3.2 代码实现
2.3.2.1 生成者

package com.liu.test;

import com.liu.rabbitmq.RabbitMqApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Created by Administrator on 2019/8/20 0020.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RabbitMqApplication.class)
public class ProducerTest2 {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Test
   public void sendMsg() throws InterruptedException {
       for (int i = 0;i<3;i++){
           //Thread.sleep(100);
           rabbitTemplate.convertAndSend("dahai",null,"rabbitmq hello world!"+i);
       }


   }



}



2.3.2.2 消费者

1号消费者:


package rabbitmq.customer;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/8/20 0020.
 */
@Component
@RabbitListener(queues = "xiaozhang")
public class Customer11 {

    @RabbitHandler
    public void getMsg(String msg){
        System.out.println( "xiaozhang,消费消息:"+msg);
    }

}



2号消费者:

package rabbitmq.customer;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/8/20 0020.
 */
@Component
@RabbitListener(queues = "xiaowang")
public class Customer12 {

    @RabbitHandler
    public void getMsg(String msg){
        System.out.println( "xiaowang,消费消息:"+msg);
    }

}




3号消费者:

package rabbitmq.customer;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/8/20 0020.
 */
@Component
@RabbitListener(queues = "xiaowu")
public class Customer13 {

    @RabbitHandler
    public void getMsg(String msg){
        System.out.println( "xiaowu,消费消息:"+msg);
    }

}



2.3.2.3 rabbitmq 结构

在这里插入图片描述

2.3.2.4 测试结果
xiaowang,消费消息:rabbitmq hello world!0
xiaowu,消费消息:rabbitmq hello world!0
xiaowang,消费消息:rabbitmq hello world!1
xiaowang,消费消息:rabbitmq hello world!2
xiaowu,消费消息:rabbitmq hello world!1
xiaowu,消费消息:rabbitmq hello world!2
xiaozhang,消费消息:rabbitmq hello world!0
xiaozhang,消费消息:rabbitmq hello world!1
xiaozhang,消费消息:rabbitmq hello world!2

2.4 主题模式(Topic)
2.4.1 什么是主题模式

任何发送到Topic Exchange的消息都会被转发到所有关心RouteKey中指定话题的Queue

在这里插入图片描述

如上图所示
此类交换器使得来自不同的源头的消息可以到达一个对列,其实说的更明白一点就是模糊匹配的意思,例如:上图中红色对列的routekey为usa.#,#代表匹配任意字符,但是要想消息能到达此对列,usa.必须匹配后面的#好可以随意。图中usa.newsusa.weather,都能找到红色队列,符号# 匹配一个或多个词,符号* 匹配不多不少一个词。因此usa.# 能够匹配到usa.news.XXX ,但是usa.* 只会匹配到usa.XXX 。
注:
交换器说到底是一个名称与队列绑定的列表。当消息发布到交换器时,实际上是由你所连接的信道,将消息路由键同交换器上绑定的列表进行比较,最后路由消息。任何发送到Topic Exchange的消息都会被转发到所有关心RouteKey中指定话题的Queue上
1.这种模式较为复杂,简单来说,就是每个队列都有其关心的主题,所有的消息都带有一个“标题”(RouteKey),Exchange会将消息转发到所有关注主题能与RouteKey模糊匹配的队列。
2.这种模式需要RouteKey,也许要提前绑定Exchange与Queue。
3.在进行绑定时,要提供一个该队列关心的主题,如“#.log.#”表示该队列关心所有涉及log的消息(一个RouteKey为”MQ.log.error”的消息会被转发到该队列)。

4.“#”表示0个或若干个关键字,“”表示一个关键字。如“log.”能与“log.warn”匹配,无法与“log.warn.timeout”匹配;但是“log.#”能与上述两者匹配。
5.同样,如果Exchange没有发现能够与RouteKey匹配的Queue,则会抛弃此消息

在这里插入图片描述

2.4.2 上代码
2.4.2.1 消费者

消费者1号

package rabbitmq.top;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/8/21 0021.
 */
@Component
@Slf4j
@RabbitListener(queues = "topict01")
public class Customer001 {

    @RabbitHandler
    public void getMsg(String msg){
        System.out.println( "topict01,消费消息:"+msg);
    }

}

消费者2号

package rabbitmq.top;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/8/21 0021.
 */
@Component
@Slf4j
@RabbitListener(queues = "topict02")
public class Customer002 {

    @RabbitHandler
    public void getMsg(String msg){
        System.out.println( "topict02,消费消息:"+msg);
    }

}

消费者3号



package rabbitmq.top;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/8/21 0021.
 */
@Component
@Slf4j
@RabbitListener(queues = "topic03")
public class Customer003 {

    @RabbitHandler
    public void getMsg(String msg){
        System.out.println( "topict03,消费消息:"+msg);
    }

}


2.4.2.2 生产者


package com.liu.test;

import com.liu.rabbitmq.RabbitMqApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 测试主题模式
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RabbitMqApplication.class)
public class ProducerTest3 {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Test
   public void sendMsgtopic01() {

        rabbitTemplate.convertAndSend("topictest","good.aaa","主题模式");
        //只被1号消费者消费
   }
    

    @Test
    public void sendMsgtopic02() {

        rabbitTemplate.convertAndSend("topictest","123.fdf.log","主题模式");
        // 只被二号消费者消费
    }

    @Test
    public void sendMsgtopic03() {

        rabbitTemplate.convertAndSend("topictest","good.log","主题模式");
      // 1、2、3 号消费者都 消费
    }



}


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值