版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、基于Spring WebFlux和Cloud的反应式微服务开发 Spring WebFlux和Spring Cloud进行反应式微服务开发摘要:如果你想用Spring的最新和最好的工具开始使用反应式微服务,那么这篇文章就是为你准备的! 我已经在一年前的 HYPERLINK /2017/02/16/reactive-microservices-with-spring-5/ Reactive microservices with Spring 5 这篇文章中描述了Spring对反应堆的支持。当时,Spring WebFlux项目一直处于积极的发展阶段,现在,在Spring 5正式发布之后,它在这个
2、版本是非常值得关注的。 此外,我们将尝试把反应式微服务放入Spring Cloud组件中,其中包含诸如Eureka服务发现,使用Spring Cloud Commons LoadBalanced 进行负载均衡以及使用Spring Cloud Gateway(也基于WebFlux和Netty)的API网关等元素,。 我们还将以Spring Data Reactive Mongo项目为例,介绍Spring对NoSQL数据库的反应堆支持。 我们的体系结构示例图如下,它包含两个微服务,一个服务发现,一个网关和MongoDB数据库。 源代码 HYPERLINK /piomin/sample-spring
3、-cloud-webflux.git sample-spring-cloud-webflux通常在GitHub上的一样可用。接下来,我们进一步来描述创建上述系统的步骤。第1步:使用Spring WebFlux构建反应式应用程序为了在项目中使用库Spring WebFlux,我们应该将 spring-boot-starter-webflux 添加到依赖关系中。 它包括一些依赖库,如Reactor或Netty服务器。org.springframework.bootspring-boot-starter-webfluxREST控制器看起来与同步Web服务定义的控制器非常相似。 唯一的区别在于返回对象
4、的类型。 如果我们返回单个对象,将使用Mono类的实例,如果我们返回的是多个对象,比如是一个列表,将返回一个Flux类的实例。 由于Spring Data Reactive Mongo,我们不需要做任何事情,只需调用相应接口上的所需方法即可。 实例代码如下:RestControllerpublic class AccountController private static final Logger LOGGER = LoggerFactory.getLogger(AccountController.class); Autowiredprivate AccountRepository repo
5、sitory; GetMapping(/customer/customer)public Flux findByCustomer(PathVariable(customer) String customerId) LOGGER.info(findByCustomer: customerId=, customerId);return repository.findByCustomerId(customerId);GetMappingpublic Flux findAll() LOGGER.info(findAll); return repository.findAll();GetMapping(
6、/id)public Mono findById(PathVariable(id) String id) LOGGER.info(findById: id=, id);return repository.findById(id);PostMappingpublic Mono create(RequestBody Account account) LOGGER.info(create: , account);return repository.save(account);第2步:使用Spring Data Reactive Mongo将应用程序与数据库集成应用程序和数据库之间的集成实现也非常简单
7、。 首先,我们需要在项目依赖项中添加相关数据库依赖 spring-boot-starter-data-mongodb-reactive 。org.springframework.bootspring-boot-starter-data-mongodb-reactive添加依赖过后,Mongo将自动支持响应式应用。 下一步是使用ORM映射声明一个实体。 以下类也作为AccountController的响应返回。Documentpublic class Account Idprivate String id; private String number; private String custom
8、erId; private int amount;.最后,我们可以创建一个扩展ReactiveCrudRepository的接口。 它遵循Spring Data JPA实现的模式,并提供了一些CRUD操作的基本方法。 它还允许我们自定义方法,这些名称会自动映射到查询。与标准Spring Data JPA库相比唯一的区别在于方法签名。 这些对象将由Mono和Flux进行包装。public interface AccountRepository extends ReactiveCrudRepository Flux findByCustomerId(String customerId);在这个例子
9、中,我使用了Docker容器在本地运行MongoDB。 因为我使用Docker Toolkit在Windows上运行Docker,所以Docker机器的默认地址是00。 这是application.yml文件中数据源的配置。spring:data:mongodb:uri: mongodb:/00/test步骤3:使用Eureka启用服务发现与 Spring Cloud Eureka 的集成非常类似于传统的REST微服务。 要启用发现客户端功能,我们应该首先将启动器 spring-cloud-starter-netflix-eureka-client 添加到项目依赖项中。org.springfr
10、amework.cloudspring-cloud-starter-netflix-eureka-client然后我们必须使用 EnableDiscoveryClient 这个注解来启用它的功能。SpringBootApplication EnableDiscoveryClientpublic class AccountApplication public static void main(String args) SpringApplication.run(AccountApplication.class, args);微服务将自动在Eureka注册中心进行注册。 当然,我们可能会运行每个服
11、务的多个实例。 以下是运行 account-service 实例和 customer-service 服务实例后的Eureka Dashboard 仪表板界面(http:/ localhost:8761)。 这里将不详细讲解使用嵌入式Eureka服务器运行应用程序的细节。 有关详细信息,请参阅我之前的文章, HYPERLINK /articles/quick-guide-to-microservices-with-spring-boot-20-e Spring Boot 2.0的微服务快速指南,Eureka和Spring Cloud。 Eureka服务器可作为 adiscovery-servi
12、ce 模块使用。第4步:使用WebClient进行反应性微服务之间的服务间通信Spring WebFlux项目中的WebClient实现了一个服务间通信。 与RestTemplate相同,您应该使用Spring Cloud Commons LoadBalanced 对其进行注解。 它支持使用Netflix OSS Ribbon客户端与服务发现和负载均衡进行集成。 所以,第一步是使用 LoadBalanced 注解声明一个客户端构建器。Bean LoadBalancedpublic WebClient.Builder loadBalancedWebClientBuilder() return W
13、ebClient.builder();然后我们可以将WebClientBuilder注入到REST控制器中。 通过GET / id / with-accounts实现与 account-service 通信,首先我们使用一个基于响应式的Spring Data repository来搜索客户实体。 它返回Mono对象,而WebClient返回Flux。 现在,我们的主要目的是将这些内容合并到订阅者,并从Flux中返回一个包含帐户列表的Mono对象。 下面的代码片段说明了我如何使用WebClient与另一个微服务进行通信,然后将响应和结果合并到单个Mono对象。 这种合并可以用更“优雅”的方式完成
14、,所以你可以随意创建一个推送请求。Autowiredprivate WebClient.Builder webClientBuilder; GetMapping(/id/with-accounts)public Mono findByIdWithAccounts(PathVariable(id) String id) LOGGER.info(findByIdWithAccounts: id=, id);Flux accounts = webClientBuilder.build().get().uri( HYPERLINK http:/account-service/customer/ htt
15、p:/account-service/customer/customer, id).re trieve().bodyToFlux(Account.class);return accounts.collectList().map(a - new Customer(a).mergeWith(repository.findById(id).collectList().map(CustomerMapper:map);第5步:使用Spring Cloud Gateway构建API网关Spring Cloud Gateway是最新的Spring Cloud项目之一。 它建立在Spring WebFlux的
16、基础之上,并且由于这一点,我们可以将它用作基于反应式微服务的入口。 与Spring WebFlux应用程序类似,它在嵌入式Netty服务器上运行。 要使用Spring Boot应用程序启用它,只需在您的项目中包含以下依赖项。org.springframework.cloudspring-cloud-starter-gateway我们还应该启用发现客户端,以便网关能够获取已注册的微服务列表。 但是,不需要在Eureka中注册网关的应用程序。 要禁用注册,可以在application.yml文件中将属性 eureka.client.registerWithEureka 设置为 false 。Spr
17、ingBootApplication EnableDiscoveryClientpublic class GatewayApplication public static void main(String args) SpringApplication.run(GatewayApplication.class, args);默认情况下,Spring Cloud Gateway不支持与服务发现的集成。要启用它,我们应该将属性 spring.cloud.gateway.discovery.locator.enabled 设置为true。现在,应该完成的最后一件事情就是路由器的配置。 Spring
18、Cloud Gateway提供了两种可以在路由中配置的组件:filters(过滤器)和predicates(谓词)。 Predicates用于将HTTP请求与路由进行匹配,而过滤器可用于在发送请求之前或之后修改请求和响应。这是网关的完整配置。它启用服务发现位置,并根据服务注册表中的条目定义两种路由。我们使用Path Route Predicate工厂来匹配传入的请求,并使用RewritePath GatewayFilter 工厂来修改请求的路径,以使其匹配相应的服务格式(端点显示在路径/下,而网关将它们暴露在路径下/account 和/customer下)。spring:cloud:gatew
19、ay:discovery:locator:enabled: true routes:id: account-serviceuri: lb:/account-service predicates:Path=/account/* filters:RewritePath=/account/(?.*), /$pathid: customer-serviceuri: lb:/customer-service predicates:Path=/customer/* filters:RewritePath=/customer/(?.*), /$path第6步:测试样本系统account-servicecus
20、tomer-在做一些测试之前,让我们回顾一下我们的示例系统。 我们有两个微服务 -,service - 使用MongoDB作为数据库。 微服务customer-service调用account-service暴露的端点GET / customer / customer。 account-service的URL来自Eureka。 整个系统隐藏在网关后面,该网关位于localhost:8090的地址下。 现在,第一步是在Docker容器上运行MongoDB。 执行以下命令后, Mongo在地址00:27017下可用。$ docker run -d -name mongo -p 27017:2701
21、7 mongo然后我们可以继续运行 discovery-service 。 Eureka在其默认地址localhost:8761下可用。 您可以使用IDE运行它,或者执行命令 java -jar target / discovery-service-1.0-SNAPHOT.jar 。 同样的适用于我们的示例微服务。 但是,account-service需要在两个实例中进行通信,所以当使用-Dserver.port VM参数运行第二个实例时,您需要覆盖默认的HTTP端口,例如 java -jar -Dserver.port = 2223 target /account- service-1.0-
22、SNAPSHOT.jar 。 最后,在运行网关服务之后,我们可以添加一些测试数据。$ curl -header Content-Type: application/json -request POST -data firstName: John,lastName: Scott,age: 30 http:/localhost:8090/customerid: 5aec1debfa656c0b38b952b4,firstName: John,lastName: Scott,age: 30,accounts: null$ curl -header Content-Type: application/
23、json -request POST -data number: 1234567890,amount: 5000,customerId: 5aec1debfa656c0b38b952b4 http:/localhost:8090/accountid: 5aec1e86fa656c11d4c655fb,number: 1234567892,customerId: 5aec1debfa656c0b38b952b4,amoun t: 5000$ curl -header Content-Type: application/json -request POST -data number: 1234567891,amount: 12000,customerId: 5aec1debfa656c0b38b952b4 http:/localhost:8090/accountid: 5aec1e91fa656c11d4c655fc,number: 1234567892,customerId: 5aec1debfa656c0b38b952b4,amoun t: 12000$ curl -header Content-Type: application/json -request
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026年农村体育工作规范测试题库
- 2026年科技发展趋势报告测试题库
- 2026年招聘考试知识点解析及模拟问答
- 2026年经济法中级职称考试精讲笔记与习题集
- 2026年境外投资项目核准与备案常见问题解答
- 2026年特殊教育教师招聘面试结构化问答
- 2026年窗口单位免证办服务承诺知识题
- 2026年乡村振兴战略实施要点专题考核题库
- 【苏教版】-小学一年级数学下册-第1课时 两位数加、减整十数
- 2026年服务业客户服务流程简化方案
- 12.1至12.4 集员辨识的定义及发展
- 房车全车电路施工技术交底
- 基于复杂网络的城市轨道交通-公交网络鲁棒性分析与优化
- 高铁站建筑节能方案设计
- 酒店安全管理制度
- 电动车逆行知识培训内容课件
- 医养中心突发事件应急预案
- 2025房屋买卖合同范本(下载)
- 2025年哈尔滨工业大学管理服务岗位招聘考试笔试试题(含答案)
- (2025年标准)山地开路协议书
- 2025年陕西高中学业水平合格性考试化学试卷真题(含答案)
评论
0/150
提交评论