• sb_cloud_stream

  • Spring Cloud Stream 是一个构建消息驱动微服务的框架

    • 应用程序通过 inputs 或者 outputs 来与 Spring Cloud Stream 中binder 交互,通过我们配置来 binding ,而 Spring Cloud Stream 的 binder 负责与消息中间件交互。
    • 通过使用Spring Integration来连接消息代理中间件以实现消息事件驱动。Spring Cloud Stream 为一些供应商的消息中间件产品提供了个性化的自动化配置实现,引用了发布-订阅、消费组、分区的三个核心概念。目前仅支持RabbitMQ、Kafka。
  • 为什么需要SpringCloud Stream消息驱动呢?

比方说我们用到了RabbitMQ和Kafka,由于这两个消息中间件的架构上的不同,像RabbitMQ有exchange,kafka有Topic,partitions分区,这些中间件的差异性导致我们实际项目开发给我们造成了一定的困扰,我们如果用了两个消息队列的其中一种,

后面的业务需求,我想往另外一种消息队列进行迁移,这时候无疑就是一个灾难性的,一大堆东西都要重新推倒重新做,因为它跟我们的系统耦合了,这时候springcloud Stream给我们提供了一种解耦合的方式。

 
 

    •   Spring Cloud Stream由一个中间件中立的核组成。应用通过Spring Cloud Stream插入的input(相当于消费者consumer,它是从队列中接收消息的)和output(相当于生产者producer,它是从队列中发送消息的。)通道与外界交流。

        通道通过指定中间件的Binder实现与外部代理连接。业务开发者不再关注具体消息中间件,只需关注Binder对应用程序提供的抽象概念来使用消息中间件实现业务即可

  

 
 
  • 1.基础消息发送消费

 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5.  
  6. <groupId>com.huarui</groupId>
  7. <artifactId>sb_cloud_stream</artifactId>
  8. <version>0.0.1-SNAPSHOT</version>
  9. <name>sb_cloud_stream</name>
  10. <description>Demo project for Spring Boot</description>
  11.  
  12. <parent>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-parent</artifactId>
  15. <version>1.5.13.RELEASE</version>
  16. <relativePath/> <!-- lookup parent from repository -->
  17. </parent>
  18.  
  19. <properties>
  20. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  21. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  22. <java.version>1.8</java.version>
  23. <spring-cloud.version>Edgware.SR3</spring-cloud.version>
  24. </properties>
  25.  
  26. <dependencies>
  27.  
  28. <!-- rabbit -->
  29. <dependency>
  30. <groupId>org.springframework.cloud</groupId>
  31. <artifactId>spring-cloud-starter-bus-amqp</artifactId>
  32. </dependency>
  33.  
  34. <!-- stream -->
  35. <dependency>
  36. <groupId>org.springframework.cloud</groupId>
  37. <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
  38. </dependency>
  39.  
  40. <!-- eureka client -->
  41. <dependency>
  42. <groupId>org.springframework.cloud</groupId>
  43. <artifactId>spring-cloud-starter-eureka</artifactId>
  44. </dependency>
  45.  
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. </dependencies>
  52.  
  53. <dependencyManagement>
  54. <dependencies>
  55. <dependency>
  56. <groupId>org.springframework.cloud</groupId>
  57. <artifactId>spring-cloud-dependencies</artifactId>
  58. <version>${spring-cloud.version}</version>
  59. <type>pom</type>
  60. <scope>import</scope>
  61. </dependency>
  62. </dependencies>
  63. </dependencyManagement>
  64.  
  65. <build>
  66. <plugins>
  67. <plugin>
  68. <groupId>org.springframework.boot</groupId>
  69. <artifactId>spring-boot-maven-plugin</artifactId>
  70. </plugin>
  71. </plugins>
  72. </build>
  73.  
  74. </project>

pom.xml

  1. 1 spring:
  2. 2 application:
  3. 3 name: sb_cloud_config_client
  4. 4 # #RebbitMq
  5. 5 rabbitmq:
  6. 6 host: 39.108.85.204
  7. 7 port: 5672
  8. 8 username: guest
  9. 9 password: guest
  10. 10
  11. 11
  12. 12 eureka:
  13. 13 client:
  14. 14 serviceUrl:
  15. 15 defaultZone: http://39.108.85.204:8761/eureka/
  16. 16 instance:
  17. 17 #注册时使用ip而不是主机名
  18. 18 prefer-ip-address: true
  19. 19 #指定此实例的ip
  20. 20 #ip-address: ip
  21. 21 server:
  22. 22 port: 9004

application.yml

  1. public class Girl implements Serializable {
  2.  
  3. private String id;
  4. private String name;
  5. private Date date;
  6.  
  7. public Girl(){
  8.  
  9. }
  10.  
  11. public Girl(String id, String name, Date date) {
  12. this.id = id;
  13. this.name = name;
  14. this.date = date;
  15. }
  16.  
  17. public String getId() {
  18. return id;
  19. }
  20.  
  21. public void setId(String id) {
  22. this.id = id;
  23. }
  24.  
  25. public String getName() {
  26. return name;
  27. }
  28.  
  29. public void setName(String name) {
  30. this.name = name;
  31. }
  32.  
  33. public Date getDate() {
  34. return date;
  35. }
  36.  
  37. public void setDate(Date date) {
  38. this.date = date;
  39. }
  40.  
  41. @Override
  42. public String toString() {
  43. return "Girl{" +
  44. "id='" + id + '\'' +
  45. ", name='" + name + '\'' +
  46. ", date=" + date +
  47. '}';
  48. }
  49. }

Girl.java

  1. package com.huarui.util;
  2.  
  3. import com.fasterxml.jackson.core.JsonFactory;
  4. import com.fasterxml.jackson.core.JsonParseException;
  5. import com.fasterxml.jackson.core.type.TypeReference;
  6. import com.fasterxml.jackson.databind.JsonMappingException;
  7. import com.fasterxml.jackson.databind.ObjectMapper;
  8. import com.fasterxml.jackson.databind.type.TypeFactory;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11.  
  12. import java.io.IOException;
  13. import java.text.SimpleDateFormat;
  14. import java.util.ArrayList;
  15. import java.util.HashMap;
  16. import java.util.List;
  17. import java.util.Map;
  18.  
  19. public class JsonUtils {
  20.  
  21. private static Logger log = LoggerFactory.getLogger(JsonUtils.class);
  22. private static JsonFactory jsonfactory = new JsonFactory();
  23. private static ObjectMapper mapper = new ObjectMapper(jsonfactory);
  24.  
  25. public static <T> T parseObject(String json,Class<T> clzz) {
  26. //设置JSON时间格式
  27. SimpleDateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  28. mapper.setDateFormat(myDateFormat);
  29. try {
  30. return mapper.readValue(json, clzz);
  31. } catch (JsonParseException e) {
  32. e.printStackTrace();
  33. } catch (JsonMappingException e) {
  34. e.printStackTrace();
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. return null;
  39. }
  40.  
  41. /**
  42. * json转map
  43. *
  44. * @param json
  45. * @return
  46. */
  47. public static Map<String,Object> parseMap(String json){
  48. TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {};
  49. try {
  50. return mapper.readValue(json, typeRef);
  51. } catch (JsonParseException e) {
  52. log.error("字符串转json出错!"+json, e);
  53. } catch (JsonMappingException e) {
  54. log.error("json映射map出错!"+json, e);
  55. } catch (IOException e) {
  56. log.error("json转map流错误!"+json, e);
  57. }
  58. return null;
  59. }
  60.  
  61. public static <T> List<T> parseList(String json,Class<?> clazz){
  62. TypeFactory t = TypeFactory.defaultInstance();
  63. try {
  64. List<T> list = mapper.readValue(json,t.constructCollectionType(ArrayList.class,clazz));
  65. return list;
  66. } catch (JsonParseException e) {
  67. e.printStackTrace();
  68. } catch (JsonMappingException e) {
  69. e.printStackTrace();
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. return null;
  74. }
  75.  
  76. /**
  77. * 对像转json字符串
  78. *
  79. * @param obj
  80. * @return
  81. */
  82. public static String parseString(Object obj){
  83. String result = null;
  84. try {
  85. SimpleDateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  86. mapper.setDateFormat(myDateFormat);
  87. result = mapper.writeValueAsString(obj);
  88. } catch (JsonParseException e) {
  89. log.error("字符串转json出错!", e);
  90. } catch (JsonMappingException e) {
  91. log.error("json映射map出错!", e);
  92. } catch (IOException e) {
  93. log.error("json转map流错误!", e);
  94. }
  95. return result;
  96. }
  97. }

JsonUtils.java

  1. package com.huarui.message;
  2.  
  3. import org.springframework.cloud.stream.annotation.Input;
  4. import org.springframework.cloud.stream.annotation.Output;
  5. import org.springframework.messaging.MessageChannel;
  6. import org.springframework.messaging.SubscribableChannel;
  7.  
  8. /**
  9. * 自定义input output
  10. */
  11. public interface StreamClient {
  12.  
  13. public static final String INPUT = "myinput";
  14.  
  15. public static final String OUTPUT = "myoutput";
  16.  
  17. public static final String INPUTTO = "myinputto";
  18.  
  19. public static final String OUTPUTTO = "myoutputto";
  20.  
  21. /**
  22. * 相当于消费者consumer,它是从队列中接收消息的
  23. */
  24. @Input(INPUT)
  25. SubscribableChannel input();
  26.  
  27. /**
  28. * 相当于生产者producer,它是从队列中发送消息的
  29. */
  30. @Output(OUTPUT)
  31. MessageChannel output();
  32.  
  33. }
  1. @Component
  2. @EnableBinding(StreamClient.class)
  3. public class StreamReceiver {
  4.  
  5. /**
  6. * 基本 INPUT
  7. * @param girlStr
  8. */
  9. @StreamListener(StreamClient.INPUT)
  10. public void process(String girlStr){
  11. Girl girl = JsonUtils.parseObject(girlStr, Girl.class);
  12. System.out.println("process 收到: "+girl);
  13. }
  14. }
  1. @RestController
  2. public class SendMessageController {
  3.  
  4. @Autowired
  5. private StreamClient streamClient;
  6.  
  7. @GetMapping("/sendGirl/{name}")
  8. public String sendGirl(@PathVariable String name){
  9. Girl girl = new Girl(UUID.randomUUID().toString(),name,new Date());
  10. streamClient.output().send(MessageBuilder.withPayload(girl).build());
  11. return name+" send ok";
  12. }
  13. }
  • 避免启动项目时找不到该队列,手动创建 myinput队列

访问  http://localhost:9004/sendGirl/huahua 可见消息发送 并被消费,控制台打印的消息就可以证明

  • 2.消息分组 一条消息只让组内一个实例消费

  1. spring:
  2. jackson:
  3. date-format: yyyy-MM-dd HH:mm:ss
  4. time-zon: GMT+8
  5. application:
  6. name: sb_cloud_config_client
  7. # #RebbitMq
  8. rabbitmq:
  9. host: 39.108.85.204
  10. port: 5672
  11. username: guest
  12. password: guest
  13. cloud:
  14. stream:
  15. bindings:
  16. myoutput: # 自定义output
  17. content-type: application/json #消息发送的格式 发送端指定即可
  18. destination: sb-cloud-stream
  19. myinput: # 自定义input
  20. destination: sb-cloud-stream
  21. group: girlfriend #分组 同一组的消息只有一个实例接收

yml配置文件中添加group 即可实现。

  • 3.接收消息后  并回馈消息

  1. spring:
  2. jackson:
  3. date-format: yyyy-MM-dd HH:mm:ss
  4. time-zon: GMT+8
  5. application:
  6. name: sb_cloud_config_client
  7. # #RebbitMq
  8. rabbitmq:
  9. host: 39.108.85.204
  10. port: 5672
  11. username: guest
  12. password: guest
  13. cloud:
  14. stream:
  15. bindings:
  16. myoutput: # 自定义output
  17. content-type: application/json #消息发送的格式 发送端指定即可
  18. destination: sb-cloud-stream
  19. myinput: # 自定义input
  20. destination: sb-cloud-stream
  21. group: girlfriend #分组 同一组的消息只有一个实例接收
  22. myoutputto: # 自定义output (回馈使用)
  23. content-type: application/json #消息发送的格式 发送端指定即可
  24. destination: sb-cloud-stream-to
  25. myinputto: # 自定义input(回馈使用)
  26. destination: sb-cloud-stream-to
  1. public interface StreamClient {
  2.  
  3. public static final String INPUT = "myinput";
  4.  
  5. public static final String OUTPUT = "myoutput";
  6.  
  7. public static final String INPUTTO = "myinputto";
  8.  
  9. public static final String OUTPUTTO = "myoutputto";
  10.  
  11. /**
  12. * 相当于消费者consumer,它是从队列中接收消息的
  13. */
  14. @Input(INPUT)
  15. SubscribableChannel input();
  16.  
  17. /**
  18. * 相当于生产者producer,它是从队列中发送消息的
  19. */
  20. @Output(OUTPUT)
  21. MessageChannel output();
  22.  
  23. /**
  24. * 相当于消费者consumer,它是从队列中接收消息的 (反馈使用)
  25. */
  26. @Input(INPUTTO)
  27. SubscribableChannel inputto();
  28.  
  29. /**
  30. * 相当于生产者producer,它是从队列中发送消息的 (反馈使用)
  31. */
  32. @Output(OUTPUTTO)
  33. MessageChannel outputto();
  34.  
  35. }
  1. package com.huarui.message;
  2.  
  3. import com.huarui.entity.Girl;
  4. import com.huarui.util.JsonUtils;
  5. import org.springframework.cloud.stream.annotation.EnableBinding;
  6. import org.springframework.cloud.stream.annotation.StreamListener;
  7. import org.springframework.messaging.handler.annotation.SendTo;
  8. import org.springframework.stereotype.Component;
  9.  
  10. /**
  11. * Created by lihui on 2019/2/28.
  12. */
  13.  
  14. @Component
  15. @EnableBinding(StreamClient.class)
  16. public class StreamReceiver {
  17.  
  18. /**
  19. * 基本 INPUT
  20. * @param girlStr
  21. */
  22. @StreamListener(StreamClient.INPUT)
  23. public void process(String girlStr){
  24. Girl girl = JsonUtils.parseObject(girlStr, Girl.class);
  25. System.out.println("process 收到: "+girl);
  26. }
  27.  
  28. /**
  29. * 我们接收到消息后,给别人一个反馈
  30. * SpringCloud stream 给我们提供了一个SendTo注解可以帮我们干这些事情
  31. * @param girlStr
  32. * @return
  33. */
  34. @StreamListener(StreamClient.INPUTTO)
  35. @SendTo(StreamClient.OUTPUTTO)
  36. public String processTo(String girlStr){
  37. Girl girl = JsonUtils.parseObject(girlStr, Girl.class);
  38. System.out.println("收到: "+girl);
  39. return JsonUtils.parseString(girl);
  40. }
  41.  
  42. @StreamListener(StreamClient.OUTPUTTO)
  43. public void process2(String girlStr){
  44. Girl girl = JsonUtils.parseObject(girlStr, Girl.class);
  45. System.out.println("ta 已收到: "+girl);
  46. }
  47.  
  48. }

@SendTo 注解就能实现消息接收后回馈消息, return 返回值就是回馈的消息

 访问  http://localhost:9004/sendGirlTo/huahua 可见消息被消费后 并回馈了一条消息,控制台打印的消息就可以证明


本项目地址: https://github.com/youxiu326/sb_cloud_stream.git

参考博客: https://i.cnblogs.com/EditPosts.aspx?postid=10464571&update=1

SpringCloud个人笔记-04-Stream初体验的更多相关文章

  1. Kubernetes 笔记 02 demo 初体验

    本文首发于我的公众号 Linux云计算网络(id: cloud_dev),专注于干货分享,号内有 10T 书籍和视频资源,后台回复「1024」即可领取,欢迎大家关注,二维码文末可以扫. 从前面的文章我 ...

  2. [开发笔记]-Jqplot图表初体验

    文章内容为初次使用Jqplot图表插件的测试代码,仅供参考. <html xmlns="http://www.w3.org/1999/xhtml"> <head& ...

  3. JAVA 8 新特性Stream初体验

    什么是 Stream? Stream(流)是一个来自数据源的元素队列并支持聚合操作 <strong元素队列< strong="">元素是特定类型的对象,形成一个队 ...

  4. 云中沙箱学习笔记2-ECS之初体验

    1.1 背景知识 云服务器(Elastic Compute Service, 简称ECS),是一种简单高效,处理能力可以弹性伸缩的计算服务.ECS的相关术语说明如下: --实例(Instance):是 ...

  5. Java8初体验(二)Stream语法详解

    感谢同事[天锦]的投稿.投稿请联系 tengfei@ifeve.com 上篇文章Java8初体验(一)lambda表达式语法比 较详细的介绍了lambda表达式的方方面面,细心的读者会发现那篇文章的例 ...

  6. Java8初体验(2):Stream语法详解

    原文出处: 一冰_天锦 上篇文章Java8初体验(1):lambda表达式语法比较详细的介绍了lambda表达式的方方面面,细心的读者会发现那篇文章的例子中有很多Stream的例子.这些Stream的 ...

  7. Java8初体验(二)Stream语法详解(转)

    本文转自http://ifeve.com/stream/ Java8初体验(二)Stream语法详解 感谢同事[天锦]的投稿.投稿请联系 tengfei@ifeve.com上篇文章Java8初体验(一 ...

  8. Java8初体验(二)Stream语法详解---符合人的思维模式,数据源--》stream-->干什么事(具体怎么做,就交给Stream)--》聚合

    Function.identity()是什么? // 将Stream转换成容器或Map Stream<String> stream = Stream.of("I", & ...

  9. VSTO学习笔记(十五)Office 2013 初体验

    原文:VSTO学习笔记(十五)Office 2013 初体验 Office 2013 近期发布了首个面向消费者的预览版本,我也于第一时间进行了更新试用.从此开始VSTO系列全面转向Office 201 ...

  10. Spring Boot 学习笔记1——初体验之3分钟启动你的Web应用[z]

    前言 早在去年就简单的使用了一下Spring Boot,当时就被其便捷的功能所震惊.但是那是也没有深入的研究,随着其在业界被应用的越来越广泛,因此决定好好地深入学习一下,将自己的学习心得在此记录,本文 ...

随机推荐

  1. 哈工大 计算机网络 实验三 IPv4 分组收发实验&IPv4 分组转发实验

    计算机网络实验代码与文件可见github:计算机网络实验整理 实验名称 IPv4 分组收发实验&IPv4 分组转发实验 实验目的: (注:实验报告模板中的各项内容仅供参考,可依照实际实验情况进 ...

  2. 转 Linux下安装Tomcat服务器和部署Web应用

    转载声明: http://www.cnblogs.com/xdp-gacl/p/4097608.html 一.上传Tomcat服务器

  3. c# winform中TabControl中给每个选项卡添加不同的图标(图片)

    在一个TabControl控件中,有几个选项卡,现在在每个选项卡上显示不同的图标. 1:你要现在form窗体中通过工具箱加入一个imagelist,名字为imagelist1,如下图: 2:然后在里面 ...

  4. python3中zip()的用法

    zip函数接受任意多个可迭代对象作为参数,将对象中对应的元素打包成一个tuple,然后返回一个可迭代的zip对象. 这个可迭代对象可以使用循环的方式列出其元素 若多个可迭代对象的长度不一致,则所返回的 ...

  5. .NetCore Web Api 利用ActionFilterAttribute统一接口返回值格式

    .Net Core 同 Asp.Net MVC一样有几种过滤器,这里不再赘述每个过滤器的执行顺序与作用. 在实际项目开发过程中,统一API返回值格式对前端或第三方调用将是非常必要的,在.NetCore ...

  6. 【Java分享客栈】一个包装过简历的新同事写完微信支付引起事故后果断离职了

    前言 挺长时间没发文了,因为公司有一个紧急项目要赶进度,加班如吃饭喝水,久违的进入到码农的状态. 之所以抽空来发个文,是这个项目才刚上线,时间不长却因为一位新同事的代码引起了生产环境的事故,造成了一批 ...

  7. SoftwareTeacher直播自我感想

    今天老师发布了一个链接直播是关于:同学们聊聊学习软件工程,CS 课程的问题下面是我的个人感悟和笔记 一.编程技术的提升 编程并不是一件很难的事情,就如开车一样,只有多加练习,自己的技术才能提升上去.拿 ...

  8. JavaWeb之Servlet、拦截器、监听器及编程思想

    本文包含的内容有: Servlet的理解 自定义Servlet.监听器和过滤器 三者的一点点编程设计思想 后续的学习 JavaWeb是Web开发的重要基础,对Servlet.监听器和过滤器等知识的掌握 ...

  9. OpenCv基础_三

    轮廓检测 图像金字塔 上采样,图像变大一倍,矩阵用0填充 img = cv2.imread('1,jpg') cv_show('img',img) up = cv2.pyrUp(img) cv_sho ...

  10. centos7升级openssh8.7&openssl1.1.1l脚本

    脚本下载地址或首页联系本人获取 https://files.cnblogs.com/files/blogs/705493/update_ssh.sh 需搭配openssh8.7和openssl1.1. ...