RabbitMQ(1)

182 阅读2分钟

这是我参与更文挑战的第8天,活动详情查看: 更文挑战

AMQP 的基本概念

AMQP,即Advanced Message Queuing Protocol,一个提供统一消息服务的应用层标准高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计。 AMQP(RabbitMQ)必须由三部分:交换器、队列和绑定

消息(Message):由有效载荷(playload)和标签(label)组成。其中有效载荷既传输的数据。
生产者(producer):创建消息,发布到代理服务器(Message Broker)。
代理服务器(Message Broker):接收和分发消息的应用,RabbitMQ Server就是消息代理服务器,其中包含概念很多,以RabbitMQ 为例:信道(channel)、队列(queue)、交换器(exchange)、路由键(routing key)、绑定(binding key)、虚拟主机(vhost)等。

RabbitMQ是一个实现了AMQP协议标准的开源消息代理和队列服务器。

rabbitmq 简单介绍

消息中间件

主要概念:生产者 队列 消费者
实际 生产者(producer)-交换机(Exchange)-队列(queue)-消费者(consumer)
生成者:发送消息
交换机:接收消息绑定到指定队列 队列:存储消息,先进先出 消费者:监听指定的消息队列,接收消息并处理

交换机(Exchange)四种类型:
Direct: 默认模式,最简单的模式,即创建消息队列的时候,指定一个BindingKey.当发送者发送消息的时候,指定对应的Key.当Key和消息队列的BindingKey一致的时候,消息将会被发送到该消息队列中.

topic: 转发信息依据通配符,队列和交换机绑定依据(通配符+字符串),发送消息时候只有指定的key和该模式相匹配的时候,消息才会发送到该消息队列。

headers: 在消息队列和交换机绑定的时候会指定一组键值对规则,而发送消息的时候也会指定一组键值对规则,当两组键值对规则相匹配的时候,消息会被发送到匹配的消息队列中.

Fanout: 路由广播形式,将消息发给绑定它的全部队列,即便设置了key和规则,也会被忽略.

最简单整合springboot

  1. 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. 配置
spring:
  data:
    neo4j:
      uri: bolt://192.168.1.41:7687
      username: neo4j
      password: 12345

  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

@Configuration
public class RabbitConfig {

    @Bean
    public Queue helloQueue() {
    //定义一个hello的队列,可以有4个参数,1.队列名、2.durable 持久化消息队列默认true,3.auto-delete 消息队列在没有使用时自动删除,默认false,4.exclusive 消息队列是否只在当前connnection生效,默认false
        return new Queue("hello");
    }
}
  1. 使用

发送消息

@Component
public class Sender {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);
        this.rabbitTemplate.convertAndSend("hello", context);
        

    }
}

接收消息

@Component
@RabbitListener(queues = "hello")
//@RabbitListener(queues = "#{xx}") 可使用yml自定义内容
public class Receiver {
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver : " + hello );
    }
}