栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

Spring Boot应用中整合消息中间件RabbitMQ

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot应用中整合消息中间件RabbitMQ

dota2.jpg

我们通过在Spring Boot应用中整合RabbitMQ,实现一个简单的发送、接收消息的例子来对RabbitMQ有一个直观的感受和理解。

  • 新建一个Spring Boot工程,命名为 rabbitmq-hello

  • 在 pom.xml 文件中引入如下依赖内容


    org.springframework.boot
    spring-boot-starter-amqp
  • application.properties文件中配置RabbitMQ的相关信息

spring.rabbitmq.addresses=10.110.200.29:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
  • 创建消息生产者 Sender。通过注入 AmqpTemplate 接口的实例来实现消息的发送,AmqpTemplate 接口定义了一套针对 AMQP 协议的基础操作。在 Spring Boot 中会根据配置来注入其具体实现。在该生产者中,我们会产生一个字符串,并发送到名为 hello 的队列中

@Componentpublic class Sender {    @Autowired
    private AmqpTemplate rabbitTemplate;    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);
        rabbitTemplate.convertAndSend("hello", context);
    }
}
  • 创建消息消费者 Receiver 。通过 @RabbitListener 注解定义该类对 hello 队列的监听,并用 @RabbitHandler 注解来指定对消息的处理方法

@Component@RabbitListener(queues = "hello")public class Receiver {    // 这里 process 方法名 和 hello 参数名 可以任意。
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver : " + hello);
    }
}
  • 创建配置类 RabbitConfig ,用来配置队列、交换器、路由等高级信息。这里以入门为主,以最小化配置来定义,完成一个基本的生产消费过程

@Configurationpublic class RabbitConfig {    @Bean
    public Queue helloQueue() {        return new Queue("hello");
    }
}
  • 创建应用主类

@SpringBootApplicationpublic class RabbitMQApplication {    public static void main(String[] args) {
        SpringApplication.run(RabbitMQApplication.class, args);
    }
}
  • 创建单元测试类

@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTestpublic class RabbitMQApplicationTests {    @Autowired
    private Sender sender;    @Test
    public void contextLoads() {
        sender.send();
    }
}
  • 运行单元测试类,可以在控制台看到 sender 消息被发送到了 hello 队列中。

  • 切换到主类控制台,我们看到消费者对 hello 队列的消息进行了监听,并打印了接收到的消息信息。



作者:angeChen
链接:https://www.jianshu.com/p/f42789ebb6c4


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

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

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