异步通信Broker的优点?

  • 解除耦合
  • 提升性能
  • 故障隔离
  • 流量控制

异步通信的缺点?

  • 依赖Broker的性能
  • 架构复杂,debug难度提升

RabbitMQ中的几个概念

  • cahnnel: 操作MQ的工具
  • exhange:路由消息到队列中
  • queue:缓存消息
  • virtual host:虚拟主机,是对queue、exchange等资源的逻辑分组

消息队列几种模式?

  • 大概分三个,
    • 广播模式Fanout
      • @RabbitListener(queues = “fanout.queue1”)
        public void listenFanoutQueueMessage1(String msg) throws InterruptedException {
        System.out.println(“fanout.queue1消费消息” + msg + “】”);
        }
      • @Test
        public void sendFanoutQueueMsg(){
        //消息内容
        String message = “hello 广播!”;
        //队列名称
        String queueName = “simple.queue”;
        //发送消息
        rabbitTemplate.convertAndSend(“itcast.fanout”,””,message);
        }
    • 路由模式Direct
      • @RabbitListener(bindings = @QueueBinding(
        value = @Queue(“direct.queue1”),
        exchange = @Exchange(value = “itcast.direct”, type = ExchangeTypes.DIRECT),
        key = {“blue”, “red”}
        ))
        public void listenDirectQueueMessage1(String msg) throws InterruptedException {
        System.out.println(“Direct.queue1消费消息” + msg + “】”);
        }
      • @Test
        public void sendDirectQueueMsg(){
        //消息内容
        String message = “红色警报 广播!”;
        //队列名称
        // String queueName = “simple.queue”;
        //发送消息
        rabbitTemplate.convertAndSend(“itcast.direct”,”yellow”,message);
        }
    • 话题情景(我愿称为超路由)模式Topic
      • @RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = “topic.queue1”),
        exchange = @Exchange(name = “itcast.topic”, type = ExchangeTypes.TOPIC),
        key = “china.#”
        ))
        public void listenTopicQueue1(String msg) {
        System.out.println(“消费者接收到topic.queue1的消息:【” + msg + “】”);
        }
      • @Test
        public void testSendTopicExchange() {
        // 交换机名称
        String exchangeName = “itcast.topic”;
        // 消息
        String message = “喜报!孙悟空大战哥斯拉,胜!”;
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, “china.news”, message);
        }

消息发送和消息接收的配置文件?

  • 消息发送的配置文件 :::info spring:
    rabbitmq:
    host: 192.168.150.101 # 主机名
    port: 5672 # 端口
    virtual-host: / # 虚拟主机
    username: itcast # 用户名
    password: 123321 # 密码 :::

  • 消息接收的配置文件 :::info spring:
    rabbitmq:
    host: 192.168.150.101 # 主机名
    port: 5672 # 端口
    virtual-host: / # 虚拟主机
    username: itcast # 用户名
    password: 123321 # 密码 :::

    消费者处理效率不同时,如何避免平均分配?

  • 配置文件 :::info spring:
    rabbitmq:
    listener:
    simple:
    prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息 :::