栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

SpringAMQP

SpringAMQP

概述

Spring AMQP 项目将核心 Spring 概念应用于基于 AMQP 的消息传递解决方案的开发。它提供了一个“模板”作为发送和接收消息的高级抽象。它还通过“侦听器容器”为消息驱动的 POJO 提供支持。这些库促进了 AMQP 资源的管理,同时促进了依赖注入和声明性配置的使用。在所有这些情况下,您将看到与 Spring 框架中 JMS 支持的相似之处。

该项目由两部分组成;spring-amqp 是基础抽象,spring-rabbit 是 RabbitMQ 实现。

特征
  • 用于异步处理入站消息的侦听器容器

  • RabbitTemplate 用于发送和接收消息

  • RabbitAdmin 用于自动声明队列、交换和绑定

案例

流程如下:

1. 在父工程中引入 spring- amqp 的依赖;
   
        
            org.springframework.boot
            spring-boot-starter-amqp

        

spring:
  rabbitmq:
    host: 
    port: 5672
    virtual-host: /
    username: 
    password: 

2.在publisher服务中利用RabbitTemplate发送消息到simple.queue这个队列;

   @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSimpleQueue() {
        String queueName = "simple.queue";
        String message = "hello,Spring AMQP";
        rabbitTemplate.convertAndSend(queueName,message);

    }

3.在consumer服务中配置rabbitmq,编写消费逻辑,绑定simple.queue这个队列;

spring:
  rabbitmq:
    host: 
    port: 5672
    virtual-host: /
    username: 
    password: 

@Component
public class listener {

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage(String msg)throws InterruptedException {
        System.out.println("Spring 消费者接收到的消息:{"+ msg + "}");
    }
}

 work Queue工作队列:实现一个队列绑定多个消费者

    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueue2Message(String msg)throws InterruptedException {
        System.err.println("Spring 消费者---2---接收到的消息:{"+ msg + "}"+ LocalTime.now());
        Thread.sleep(200);
    }
spring:
  rabbitmq:
    host: 192.168.211.128
    port: 5672
    virtual-host: /
    username: itcast
    password: 123321
    listener:
      simple:
        prefetch: 1 #每次只能获取一条消息,处理完才能获取下一条消息

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/327086.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号