广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring Cloud Stream简单用法
  • 919
分享到

Spring Cloud Stream简单用法

2024-04-02 19:04:59 919人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录简单使用spring cloud Stream 构建基于RocketMQ的生产者和消费者生产者消费者Stream其他特性消息发送失败的处理消费者错误处理spring Cloud

spring Cloud Stream对Spring Cloud体系中的MQ进⾏了很好的上层抽象,可以让我们与具体消息中间件解耦合,屏蔽掉了底层具体MQ消息中间件的细节差异,就像Hibernate屏蔽掉了具体数据库Mysql/oracle⼀样)。如此⼀来,我们学习开发、维护MQ都会变得轻松。⽬前Spring Cloud Stream原生⽀持RabbitMQkafka,阿里在这个基础上提供了RocketMQ的支持

简单使用Spring Cloud Stream 构建基于RocketMQ的生产者和消费者

生产者

pom文件中加入依赖


<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>

    </dependencies>

配置文件中增加关于Spring Cloud Stream binder和bindings的配置


spring:
  application:
    name: zhao-cloud-stream-producer
  cloud:
    stream:
      rocketmq:
        binder:
          name-server: 127.0.0.1:9876
        bindings:
          output:
            producer:
              group: test
              sync: true
      bindings:
        output:
          destination: stream-test-topic
          content-type: text/plain # 内容格式。这里使用 JSON

其中destination代表生产的数据发送到的topic 然后定义一个channel用于数据发送


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

public interface TestChannel {
    @Output("output")
    MessageChannel output();
}

最后构造数据发送的接口


@Controller
public class SendMessageController {
    @Resource
    private TestChannel testChannel;

    @ResponseBody
    @RequestMapping(value = "send", method = RequestMethod.GET)
    public String sendMessage() {
        String messageId = UUID.randomUUID().toString();
        Message<String> message = MessageBuilder
                .withPayload("this is a test:" + messageId)
                .setHeader(MessageConst.PROPERTY_TAGS, "test")
                .build();
        try {
            testChannel.output().send(message);
            return messageId + "发送成功";
        } catch (Exception e) {
            return messageId + "发送失败,原因:" + e.getMessage();
        }
    }
}

消费者

消费者的pom引入与生产者相同,在此不再赘述,配置时需要将stream的output修改为input并修改对应属性


spring:
  application:
    name: zhao-cloud-stream-consumer
  cloud:
    stream:
      rocketmq:
        binder:
          name-server: 127.0.0.1:9876
        bindings:
          input:
            consumer:
              tags: test
      bindings:
        input:
          destination: stream-test-topic
          content-type: text/plain # 内容格式。这里使用 jsON
          group: test

另外关于channel的构造也要做同样的修改


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

public interface TestChannel {
    @Input("input")
    SubscribableChannel input();
}

最后我在启动类中对收到的消息进行了监听


   @StreamListener("input")
    public void receiveInput(@Payload Message message) throws ValidationException {
        System.out.println("input1 receive: " + message.getPayload() + ", foo header: " + message.getHeaders().get("foo"));
    }

测试结果

file

file

Stream其他特性

消息发送失败的处理

消息发送失败后悔发送到默认的一个“topic.errors"的channel中(topic是配置的destination)。要配置消息发送失败的处理,需要将错误消息的channel打开 消费者配置如下


spring:
  application:
    name: zhao-cloud-stream-producer
  cloud:
    stream:
      rocketmq:
        binder:
          name-server: 127.0.0.1:9876
        bindings:
          output:
            producer:
              group: test
              sync: true
      bindings:
        output:
          destination: stream-test-topic
          content-type: text/plain # 内容格式。这里使用 JSON
          producer:
            errorChannelEnabled: true

在启动类中配置错误消息的Channel信息


 @Bean("stream-test-topic.errors")
    MessageChannel testoutPutErrorChannel(){
        return new PublishSubscribeChannel();
    }

新建异常处理service


import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Service
public class ErrorProducerService {

    @ServiceActivator(inputChannel = "stream-test-topic.errors")
    public void receiveProducerError(Message message){
        System.out.println("receive error msg :"+message);
    }
}

当发生异常时,由于测试类中已经将异常捕获,处理发送异常主要是在这里进行。模拟,应用与rocketMq断开的场景。可见

file file

消费者错误处理

首先增加配置为


spring:
  application:
    name: zhao-cloud-stream-producer
  cloud:
    stream:
      rocketmq:
        binder:
          name-server: 127.0.0.1:9876
        bindings:
          output:
            producer:
              group: test
              sync: true
      bindings:
        output:
          destination: stream-test-topic
          content-type: text/plain # 内容格式。这里使用 JSON
          producer:
            errorChannelEnabled: true

增加相应的模拟异常的操作


 @StreamListener("input")
    public void receiveInput(@Payload Message message) throws ValidationException {
        //System.out.println("input1 receive: " + message.getPayload() + ", foo header: " + message.getHeaders().get("foo"));
        throw new RuntimeException("oops");
    }
    @ServiceActivator(inputChannel = "stream-test-topic.test.errors")
    public void receiveConsumeError(Message message){
        System.out.println("receive error msg"+message.getPayload());
    }

file

代码地址https://GitHub.com/zhendiao/deme-code/tree/main/zp

到此这篇关于Spring Cloud Stream简单用法的文章就介绍到这了,更多相关Spring Cloud Stream使用内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Spring Cloud Stream简单用法

本文链接: https://www.lsjlt.com/news/131032.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring Cloud Stream简单用法
    目录简单使用Spring Cloud Stream 构建基于RocketMQ的生产者和消费者生产者消费者Stream其他特性消息发送失败的处理消费者错误处理Spring Cloud ...
    99+
    2022-11-12
  • Spring Cloud Stream如何使用
    本篇内容介绍了“Spring Cloud Stream如何使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!Spring Cloud Str...
    99+
    2023-06-05
  • Spring Cloud Stream怎么使用
    这篇文章主要讲解了“Spring Cloud Stream怎么使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring Cloud Stream怎么使用”吧!Spring Cloud ...
    99+
    2023-06-19
  • Spring Cloud Stream的使用细节有哪些
    Spring Cloud Stream的使用细节有哪些,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。上我们就来看看Spring Cloud Stream的一些使用细节。自定义消...
    99+
    2023-06-19
  • Spring Cloud Stream消息驱动组件使用方法介绍
    目录1、Stream解决的痛点问题2、Stream重要概念3、传统MQ模型与Stream消息驱动模型4、Stream消息通信方式及编程模型4.1、Stream消息通信方式4.2、St...
    99+
    2022-11-13
  • 【Kafka】Kafka Stream简单使用
    一、实时流式计算 1. 概念 一般流式计算会与批量计算相比较。在流式计算模型中,输入是持续的,可以认为在时间上是无界的,也就意味着,永远拿不到全量数据去做计算。同时,计算结果是持续输出的,也即计算结果在时间上也是无界的。流式计算一般对实...
    99+
    2023-08-30
    java kafka 微服务 Kafka Stream 实时流式计算
  • 如何实现Spring+ Spring cloud + SSO单点登录应用认证
    今天就跟大家聊聊有关如何实现Spring+ Spring cloud + SSO单点登录应用认证,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。不同系统的无缝隙集成,统一的sso单点登...
    99+
    2023-06-05
  • Spring Security的简单使用
    目录什么是Spring SecuritySpring Security测试SpringSecurity的使用静态资源一些其他的小东西什么是Spring Security ...
    99+
    2022-11-12
  • Spring Cloud Hystrix的基本用法大全
    目录1. Hystrix的简单使用1.1 服务降级1.2 服务熔断2. OpenFeign集成Hystrix3. Hystrix熔断原理3.1 熔断状态3.2 熔断的工作原理4. 代...
    99+
    2022-11-13
  • Spring Cloud微服务使用webSocket的方法
    webSocket webSocket长连接是一种在单个tcp连接上进行全双工通信的协议,允许双向数据推送。一般微服务提供的restful API只是对前端请求做出相应。使用web...
    99+
    2022-11-12
  • Spring Cloud OpenFeign实例介绍使用方法
    目录一. OpenFeign概述二. 使用步骤2.1 feign接口模块2.1.1依赖配置2.1.2编写FeignClient的接口, 并加@FeignCleint 注解2.2 消费...
    99+
    2022-11-13
  • Spring Boot 中的Servlet简单使用
    当使用spring-Boot时,嵌入式Servlet容器通过扫描注解的方式注册Servlet、Filter和Servlet规范的所有监听器(如HttpSessionListener监听器)。Spring boot 的主 Servlet 为 ...
    99+
    2023-05-31
    spring boot servlet
  • Spring Cloud Feign使用对象参数的方法
    本文小编为大家详细介绍“Spring Cloud Feign使用对象参数的方法”,内容详细,步骤清晰,细节处理妥当,希望这篇“Spring Cloud Feign使用对象参数的方法”文章能帮助大家解决...
    99+
    2023-06-29
  • Spring Cloud中声明式服务调用Feign的方法
    这篇文章主要介绍“Spring Cloud中声明式服务调用Feign的方法”,在日常操作中,相信很多人在Spring Cloud中声明式服务调用Feign的方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”S...
    99+
    2023-06-19
  • Spring Cloud Alibaba整合Nacos使用的方法是什么
    今天小编给大家分享一下Spring Cloud Alibaba整合Nacos使用的方法是什么的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有...
    99+
    2023-07-05
  • Spring Cloud-Feign服务调用的问题及处理方法
    概述: • Feign 是一个声明式的 REST 客户端,它用了基于接口的注解方式,很方便实现客户端配置。 • Feign 最初由 Netflix 公司提供...
    99+
    2022-11-12
  • java FastJson的简单用法
    目录1.前言1.1.FastJson的介绍:1.2.FastJson的特点:1.3.FastJson的简单说明:2.FastJson的用法2.1.JSON格式字符串与JSON对象之间...
    99+
    2022-11-12
  • 解决nacos升级spring cloud 2020.0无法使用bootstrap.yml的问题
    nacos升级spring cloud 2020.0无法使用bootstrap.yml 之前用spring cloud整合nacos,需要一个bootstrap.yml作为sprin...
    99+
    2022-11-12
  • Spring Cloud中使用Feign,@RequestBody无法继承的解决方案
    目录使用Feign,@RequestBody无法继承的问题原因分析解决方案使用feign遇到的问题1、示例2、首次访问超时问题3、FeignClient接口中使用Feign,@Req...
    99+
    2022-11-12
  • spring data jpa怎么创建方法名进行简单查询
    本文小编为大家详细介绍“spring data jpa怎么创建方法名进行简单查询”,内容详细,步骤清晰,细节处理妥当,希望这篇“spring data jpa怎么创建方法名进行简单查询”文章能帮助大家...
    99+
    2023-06-29
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作