Spring Cloud Alibaba学习笔记(12)

Stella981
• 阅读 485

什么是Spring Cloud Stream

一个用于构建消息驱动的微服务的框架

Spring Cloud Alibaba学习笔记(12)

应用程序通过 inputs 或者 outputs 来与 Spring Cloud Stream 中binder 交互,通过我们配置来 binding ,而 Spring Cloud Stream 的 binder 负责与中间件交互。所以,我们只需要搞清楚如何与 Spring Cloud Stream 交互就可以方便使用消息驱动的方式

Spring Cloud Stream编程模型

  • Destination Binder(目标绑定器)
    • 与消息中间件通信的组件
  • Destination Bindings(目标绑定)
    • Binding是连接应用程序与消息中间件的桥梁,用于消息的消费和生产,有Binder创建
  • Message(消息)

Spring Cloud Alibaba学习笔记(12)

微服务集成了Stream,Stream的Destination Binder创建了两个Binding,左边的Binding连接Rabbit MQ,右边的MQ连接Kafka。 左边的Binding从Rabbit MQ处消费消息,然后经过Application处代码的处理,把处理结果传输给Kafka。【从Rabbit MQ处消费消息,然后经过处理,生产到Kafka】

使用Spring Cloud Stream 实现消息收发

编写生产者

添加依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
</dependency>

注意groupIdcom.alibaba.cloud,而不是org.springframework.cloud

添加注解

在启动类上添加**@EnableBinding注解,其中Source**用来发送消息

@SpringBootApplication
@EnableBinding(Source.class)
public class Study01Application {
    public static void main(String[] args) {
        SpringApplication.run(Study01Application.class, args);
    }
}

添加配置

rocketmq.binder.name-server RocketMQ控制台地址 output 表示生产者,用于绑定一个topic投递消息 bindings.output.destination 指定topic

spring:
  cloud:
    stream:
      rocketmq:
        binder:
          name-server: 127.0.0.1:9876
      bindings:
        # 生产者
        output:
          # 指定topic
          destination: topic-stream

代码实现

注入Source接口,用来实现消息发送 MessageBuilder构建消息体

@Autowired
private Source source;

@GetMapping("test-stream")
public String testStream() {
    this.source.output()
            .send(
                    MessageBuilder
                            .withPayload("消息体")
                            .build()
            );
    return "testStream";
}

控制台查看

启动项目,请求之后,可以在RocketMQ控制台-消息页面看见topic为topic-stream的消息 Spring Cloud Alibaba学习笔记(12)

编写消费者

添加依赖

同生产者

添加注解

@SpringBootApplication
@EnableBinding(Sink.class)
public class Study02Application {
    public static void main(String[] args) {
        SpringApplication.run(Study02Application.class, args);
    }
}

添加配置

input表示消费者,用于绑定一个topic消费消息 destination指定topic,要与生产者的topic相对应.在使用RocketMQ时,group必填;使用其他MQ时,可以留空

spring:
  cloud:
    stream:
      rocketmq:
        binder:
          name-server: 127.0.0.1:9876
      bindings:
        # 消费者
        input:
          # 指定topic,要与生产者的topic匹配
          destination: topic-stream
          # 根据业务指定
          # 一定要设置,否则会启动报错
          # 如果使用的是其他的MQ,可以留空
          group: group-stream

代码实现

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class testStreamConsumer {
    @StreamListener(Sink.INPUT)
    public void receive(String messageBody) {
        log.info("------>" + messageBody);
    }
}

测试结果

Spring Cloud Alibaba学习笔记(12)

Spring Cloud Stream自定义接口

在以上的例子中,我们发现只可以设置一个topic,这显然满足不了实际的生产需求,所以这个时候就需要用到stream的自定义接口来实现多个“input”和“output”绑定不同的topic了。

生产者发送消息时使用的是Source接口里的output方法,而消费者接收消息时使用的是Sink接口里的input方法,并且都需要配置到启动类的@EnableBinding注解里。所以实际上我们需要自定义接口的源码与这两个接口的源码几乎一致,只是名称有所不同而已,使用上也只是将Source和Sink改为自定义的接口即可。

自定义发送消息

自定义消息发送接口

import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;

/**
 * 自定义发送消息接口
 */
public interface customizeSource {
    String CUSTOMIZE_OUTPUT = "customize-output";

    @Output(CUSTOMIZE_OUTPUT)
    MessageChannel output();
}

修改注解

在启动类的**@EnableBinding**注解上添加刚刚自定义的消息发送接口

@EnableBinding({Source.class, customizeSource.class})

修改配置

注意customize-output的值一定要与自定义消息发送接口中**@Output**注解的值相同

cloud:
  stream:
    rocketmq:
      binder:
        name-server: 127.0.0.1:9876
    bindings:
      # 生产者
      output:
        # 指定topic
        destination: topic-stream
      customize-output:
        destination: topic-stream-customize

代码实现

@Autowired
private CustomizeSource customizeSource;

@GetMapping("test-stream-customize")
public String testCustomizeStream() {
    customizeSource.output()
            .send(
                    MessageBuilder
                            .withPayload("消息体")
                            .build()
            );
    return "testStream";
}

验证

Spring Cloud Alibaba学习笔记(12)

自定义接收消息

自定义消息接收接口

import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;

/**
 * 自定义消费消息接口
 */
public interface CustomizeSink {
    String CUSTOMIZE_INPUT = "customize-input";

    @Input(CUSTOMIZE_INPUT)
    SubscribableChannel input();
}

修改注解

在启动类的**@EnableBinding**注解上添加刚刚自定义的消息接收接口

@EnableBinding({Sink.class, CustomizeSink.class})

修改配置

注意customize-input的值一定要与自定义消息发送接口中**@Input**注解的值相同

cloud:
    stream:
      rocketmq:
        binder:
          name-server: 127.0.0.1:9876

      bindings:
        # 消费者
        input:
          # 指定topic,要与生产者的topic匹配
          destination: topic-stream
          # 根据业务指定
          # 一定要设置,否则会启动报错
          # 如果使用的是其他的MQ,可以留空
          group: group-stream
        customize-input:
          destination: topic-stream-customize
          group: group-stream-customize

代码实现

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CustomizeStreamConsumer {
    @StreamListener(CustomizeSink.CUSTOMIZE_INPUT)
    public void receive(String messageBody) {
        log.info("------>自定义>" + messageBody);
    }
}

验证

Spring Cloud Alibaba学习笔记(12)

**PS:**总结来说,@EnableBinding注解的Source接口实现了发送消息,Sink接口实现了接收消息.而@EnableBinding还有一个Processor接口,Processor接口继承了Source接口和Sink接口,使用这个接口可以实现收发消息

package org.springframework.cloud.stream.messaging;

public interface Processor extends Source, Sink {
}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
2年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这