Spring Cloud Stream简单用法

 更新时间:2021年07月23日 14:50:36   作者:微瞰技术  
Spring cloud stream是为构建微服务消息驱动而产生的一种框架。Spring Cloud Stream基于Spring boot的基础上,可创建独立的、生产级别的Spring应用,并采用Spring Integration来连接消息中间件提供消息事件驱动,一起看看吧

Spring Cloud Stream对Spring Cloud体系中的Mq进⾏了很好的上层抽象,可以让我们与具体消息中间件解耦合,屏蔽掉了底层具体MQ消息中间件的细节差异,就像Hibernate屏蔽掉了具体数据库(Mysql/Oracle⼀样)。如此⼀来,我们学习、开发、维护MQ都会变得轻松。⽬前Spring Cloud Stream原生⽀持RabbitMQ和Kafka,阿里在这个基础上提供了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使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 详解Java中的Lambda表达式

    详解Java中的Lambda表达式

    Lambda表达式是Java SE 8中一个重要的新特性。这篇文章主要介绍了Java中的Lambda表达式 ,需要的朋友可以参考下
    2019-04-04
  • SpringBoot3集成MyBatis详解

    SpringBoot3集成MyBatis详解

    MyBatis是一款开源的持久层框架,它极大地简化了与数据库的交互流程,MyBatis更具灵活性,允许开发者直接使用SQL语句与数据库进行交互,本文将详细介绍在Spring Boot项目中如何集成MyBatis,以实现对数据库的轻松访问和操作,需要的朋友可以参考下
    2023-12-12
  • Spring中的@ControllerAdvice和ResponseBodyAdvice详解

    Spring中的@ControllerAdvice和ResponseBodyAdvice详解

    这篇文章主要介绍了Spring中的@ControllerAdvice和ResponseBodyAdvice详解,@ControllerAdvice作用于@Controller修饰的类里面的所有方法,ResponseBodyAdvice作用于@ResponseBody注解修饰的方法,它可以对这些方法的返回值进行修改,需要的朋友可以参考下
    2024-01-01
  • Java优化if-else代码的实战记录

    Java优化if-else代码的实战记录

    开发中经常会根据不同的参数判断走不同的逻辑业务,我们常用的方法就是if/else嵌套使用,导致每增加一个需求就加一个if,慢慢的就会发现自己写的代码中出现了大量的if/else,这篇文章主要给大家介绍了关于Java优化if-else代码的相关资料,需要的朋友可以参考下
    2021-09-09
  • eclipse的web项目实现Javaweb购物车的方法

    eclipse的web项目实现Javaweb购物车的方法

    这篇文章主要介绍了eclipse的web项目实现Javaweb购物车的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • Java如何使用正则表达式查找指定字符串

    Java如何使用正则表达式查找指定字符串

    在软件开发中正则表达式是个很有用的功能,使用正则表达式可以简化代码,省去不少时间,下面这篇文章主要给大家介绍了关于Java如何使用正则表达式查找指定字符串的相关资料,需要的朋友可以参考下
    2022-09-09
  • 详细Java批量获取微信公众号方法

    详细Java批量获取微信公众号方法

    本篇文章给大家讲解了用JAVA如何实现向爬虫一样获取微信公众号和其基本信息等,需要你正巧需要,那跟着学习参考下吧。
    2017-12-12
  • 23种设计模式(10)java组合模式

    23种设计模式(10)java组合模式

    这篇文章主要为大家详细介绍了23种设计模式之java组合模式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • JDBC三层架构深入刨析

    JDBC三层架构深入刨析

    三层架构是一种软件设计架构,是一种组织代码的手段和方法,三层架构的优点是扩展性好,复用性高;缺点是步骤多,比较繁琐;代码多,效率降低
    2022-12-12
  • WebSocket简介与消息推送

    WebSocket简介与消息推送

    这篇文章介绍了WebSocket简介与消息推送,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-12-12

最新评论