当前位置:   article > 正文

SpringCloud微服务实战之消息驱动Stream_springcloudstream消息驱动手动

springcloudstream消息驱动手动

Spring Cloud Stream 是一个用来为微服务应用构建消息驱动能力的架构,它为一些供应商的消息中间件产品提供了个性化的自动化配置实现,并且引入了发布-订阅、消费组以及分区这三个核心概念。简单的说,Spring Cloud Stream本质上是整合了Spring Boot和Spring Integration,实现了一套轻量级的消息驱动的微服务框架。

一、构建一个简单服务

1、创建Maven项目SpringCloud-Stream
这里写图片描述

2、在pom中添加依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- add stream depend -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
        </dependency>
    </dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3、编写消息接收类用于接收来自RabbitMQ的消息。@EnableBinding注解用来指定一个或者多个定义了@Input或@Output注解的接口,以此实现对消息通道的绑定。

@EnableBinding(Sink.class)
public class SinkRecevier {

    @StreamListener(Sink.INPUT)
    public void receive(Object payload){
        System.out.println("Recevied:"+payload);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4、创建主类

@SpringBootApplication
public class StreamApplication {

    public static void main(String[] args) {
        SpringApplication.run(StreamApplication.class, args);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

5、启动项目测试
这里写图片描述

  • 启动时,控制台输出日志中可以看出使用guest用户创建了一个指向127.0.0.1:5672的连接。可以通过配置文件application.properties来对RabbitMQ的连接信息以及通道等进行配置。
spring.cloud.stream.bindings.input.destination=raw-sensor-data

spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=springcloud
spring.rabbitmq.password=springcloud
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

这里写图片描述

  • 登录RabbiltMQ管理中心:http://localhost:15672,在connection中也可看见这个连接
    这里写图片描述

  • 在RabbitMQ管理中心,发送一条测试消息
    这里写图片描述

  • 在项目启动控制台可以看见打印出: Recevied:[B@14c7e756 此时输出的是消息对象的引用。
    这里写图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/840767
推荐阅读
相关标签
  

闽ICP备14008679号