1. 微服务

  • 微服务是一种架构风格

  • 一系列微小的服务共同组成

  • 跑在自己的进程里

  • 每个服务为独立的业务开发

  • 独立部署

  • 分布式的管理

1.1 单体架构

  • 部署在一个容器中
  • 公用一个数据库

单体架构优点:容易测试、容易部署。

单体架构缺点:开发效率低、代码维护难、部署不灵活、稳定性不高、拓展性不够。

1.2 分布式定义

  1. 指在支持应用程序和服务的开发,可以利用物理架构**由多个自治的处理元素**, **不共享主内存**,但通过网络发送消息合作

1.3 微服务架构

1.3.1 微服务架构的基础架构/组件

  • 微服务注册发现
  • 服务网关(Service Gateway)
  • 后端通用服务(也称中间层服务 Middle Tier Service)
  • 前端服务(也称边缘服务Edge Service)

2. Spring Cloud是什么

  • Spring Cloud是一个开发工具集,包含了多个子项目

    • 利用Spring Boot的开发遍历
    • 主要是基于对Netflix开源组件的进一步封装
  • Spring cloud简化了分布式开发

2.1 Spring Cloud Eureka

  • 基于Netflix做了二次封装
  • 两个组件组成:

    • Eureka Server 注册中心:提供服务注册
    • Eureka Client 服务注册:用来简化与服务器的交互

Eureka Server 注册中心

@EnableEurekaServer` 注册中心注解 。 我们启动项目后发现报错,说明这个注册中心是一个服务端, 同时也是一个客户端,他也需要找一个注册中心将自己注册上去。(自己注册自己)

  1. eureka:
  2. client:
  3. service-url: # 配置注册中心地址, 这里需要将自己注册在自己的注册中心中,启动一开始会报错,
  4. defaultZone: http://localhost:8761/eureka/
  5. register-with-eureka: false # 不需要将自己显示在注册中心中。
  6. spring:
  7. application:
  8. name: eureka
  9. server:
  10. port: 8761

每次都要将注册中心启动, 我们可以打成JAR的方式来启动它。或则在IDEA中。

Eureka Client 服务注册

@EnableDiscoveryClient 、 @EnableEurekaClient 服务注册客户端注解。

@EnableDiscoveryClient与@EnableEurekaClient区别:

  1. 订阅中心可以有eureka,zookeeper,consul等…
    @EnableDiscoveryClient基于spring-cloud-commons,
    @EnableEurekaClient基于spring-cloud-netflix

  2. 其实用更简单的话来说,
    就是如果选用的注册中心是eureka,那么就推荐@EnableEurekaClient,
    如果是其他的注册中心,那么推荐使用@EnableDiscoveryClient。

遇到客户端不能向服务器注册,在网上找了解决方案, 需要在maven中引入依赖, 便可启动成功。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>

Eureka Server端与应用端采用心跳机制,Server端会不停的检查这些client端是否在线、存活,会在一段时间内统计出上线率,当他低于某个比率的时候,就会抛出一个警告,但是还是当作上线。(在开发中会遇见服务没启动但是在注册中心中能看见)所以我们在开发环境时可以把他关掉。需要在Server端配置

  1. eureka:
  2. server: # 只是在开发环境中这样使用
  3. enable-self-preservation: false

Eureka Server高可用

Eureka Server是单台服务器,要是挂了怎末办?

解决办法:使用两个Eureka Server 相互注册。并且上面的信息会相互交换。eureka1 和eureka2 其中一个停掉了,都不会影响,但是我们的client如果只注册在了挂掉的eureka上,这个时候重启就会报错,所以在我们的client端需要配置这两个eureka地址 eureka.client.service-url:返回的是Map<String,String>所以可以这样注册:

  1. eureka:
  2. client:
  3. service-url:
  4. defaultZone: http://localhost:8761/eureka/, http://localhost:8762/eureka/

如果项目有3个注册中心:需要两两相互注册。

Eureka总结:

  • @EnableEurekaServer @EnableEurekaClient
  • 心跳检测、健康检查、负载均衡等功能
  • Eureka的高可用, 生产上建议至少两台以上。
  • 分布式系统中,服务注册中心是最重要的基础部分

分布式下服务注册的地位和原理

服务发现的两种方式

  • 客户端发现: 不需要代理的介入,同时客户端知道所有可用的服务的地址。A需要自己实现逻辑去选择B。

    • 常用的有:Eureka
  • 服务端发现: 需要代理介入,所以B和注册中心对A是不可见的,A只需要找代理发服务就行了。

    • 常用的有:Nginx、Zookeeper、Kubernetes

微服务的特点:异构

  • 不同语言
  • 不同类型的数据库

SpringCloud的服务调用方式:REST

3. 服务拆分

以商品服务和订单服务为例介绍微服务拆分中的业务功能拆分和数据拆分的注意点以及将项目模块进行多模块改造

3.1 微服务拆分的起点

业务形态不适合微服务的:

  • 系统中包含很多很多强事务场景的
  • 业务相对稳定,迭代周期长
  • 访问压力不大,可用性要求不高

康威定律: 沟通的问题会影响系统的设计。

3.2 服务拆分的方法论

扩展立方模型

  • X轴 水平复制
  • Z轴 数据分区
  • Y轴 功能解耦

如何拆 “功能”

  • 单一职责, 松耦合(服务间低耦合), 高内聚(服务内部相关的行为都集聚在一个服务内)
  • 关注点分离

    • 按职责:给服务进行分类
    • 按通用性:一些基础组件,与具体业务无关的可以划分出来做个单一的业务
    • 按粒度级别:并不是越小越好

服务和数据的关系

  • 先考虑业务功能, 在考虑对应数据
  • 无状态服务

如何拆“数据”

  • 每个微服务都有单独的数据存储:每个服务的数据库只能由该服务来访问。
  • 依据服务特点选择不同的数据库类型:(MangoDB、 ES、 MYSQL、 REDIS)
  • 难点在确定边界 :

    • 针对边界设计API
    • 依据边界权衡数据冗余(服务拆分后,订单服务需要一部分商品服务的信息,我们将商品信息里的一部分数据冗余到订单服务中,那这部分数据要如何保证一致性)。

4. 应用通信

比较HTTP REST 和 REST,同步和异步, 介绍Spirng Cloud 采用的两种HTTP方式,重点介绍Feign. 实例演示下单流程. 引出异步通信的思考.

4.1 应用间的通信

HTTP VS RPC

  • Dubbo—-RPC
  • Spring Cloud—-HTTP

SpringCloud 中服务间两种RESTful调用方式

  • RestTemplate
  • Feign

4.1.1 RestTemplate应用通信

  1. /**调用示例*/
  2. @RestController
  3. @Slf4j
  4. public class ClientController {
  5. /*第二种方式 注册中心去获取服务*/
  6. @Autowired
  7. private LoadBalancerClient loadBalancerClient;
  8. /*第三种方式RestTemplate配置在容器中*/
  9. @Autowired
  10. private RestTemplate restTemplate;
  11. @GetMapping("/getProductMsg")
  12. public String getProductMsg(){
  13. //1. 第一种方式 (直接使用restTemplate) 不适用于当同一个服务部署在多台服务器上通过负载均衡时,
  14. RestTemplate restTemplate = new RestTemplate();
  15. String response = restTemplate.getForObject("http://localhost:8080/msg", String.class);
  16. log.info("response: {} ", response);
  17. //2. 第二种方式 (通过LoadBalancerClient 在注册中心去获取服务Host, Port。然后在使用restTemplate)) 会通过负载均衡器:Ribbon实现负载均衡默认采用轮询的方式。
  18. ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
  19. serviceInstance.getHost();
  20. String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort());
  21. log.info("url = {} ", url);
  22. RestTemplate restTemplate = new RestTemplate();
  23. String response = restTemplate.getForObject(url, String.class);
  24. log.info("response: {} ", response);
  25. //3.第三种方式 通过@LoadBalanced注解, 可在restTemplate使用应用名字
  26. String response = restTemplate.getForObject("http://PRODUCT/msg", String.class);
  27. return response;
  28. }
  29. }
  1. @Component
  2. public class RestTemplateConfig {
  3. @Bean
  4. @LoadBalanced
  5. public RestTemplate restTemplate(){
  6. return new RestTemplate();
  7. }
  8. }

4.1.2 负载均衡器:Ribbon

使用客户端负载均衡器:Ribbon的有

  • RestTemplate
  • Feign
  • Zuul

Ribbon实现负载均衡的核心

  • 服务发现 (发现依赖服务的列表)
  • 服务选择规则(如何自从多个服务中选择一个有效的服务)
  • 服务监听(检测失效的服务)

Ribbon主要组件

  • ServerList
  • IRule
  • ServerListFilter

4.1.3 Feign应用通信

问题:我当前springCloud对应的feign版本为 spring-cloud-starter-openfeign

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-feign</artifactId>
  4. <version>1.4.7.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.cloud</groupId>
  8. <artifactId>spring-cloud-netflix-core</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter-openfeign</artifactId>
  13. </dependency>

并且在启动类上面加上注解: @EnableFeignClients

  1. /*声明一个接口并且 指定一个服务*/
  2. @FeignClient(name = "product")
  3. public interface ProductClient {
  4. /*指定该服务下的接口*/
  5. @GetMapping("/msg")
  6. String productMsg();
  7. }
  1. @RestController
  2. @Slf4j
  3. public class ClientControllerFeign {
  4. /*直接注入*/
  5. @Autowired
  6. private ProductClient productClient;
  7. @GetMapping("/getProductMsg")
  8. public String getProductMsg(){
  9. String s = productClient.productMsg();
  10. log.info("s = {}", s);
  11. return s;
  12. }
  13. }

Feign的使用

  • 声明式REST客户端(伪RPC)
  • 采用了基于接口的注解
  • 内部也使用了Ribbon作负载均衡

问题:

  • 不能将在PRODUCT服务里面数据库映射的实体类暴露出去。

  • 重复定义对象在多个服务中。

  • 服务给外部提供的接口@FeignClient应该由自己提供,而不是让使用该服务的服务来创建。

4.1.4 项目改造成多模块

如product服务改造成多模块后

  • product-server (所有业务逻辑service、controller)
  • product-client (对外暴露的接口)
  • product-common (公用的对象,即会被外部服务调用,也为自己提供)

4.2 同步or异步

4.2.1 安装RabbitMQ

  1. docker run -d --hostname my-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3.7.3-management

Docker

  • 从系统环境开始,自低至上打包应用
  • 轻量级,对资源的有效隔离和管理
  • 可复用, 版本化

微服务和Docker、Devops

  1. 三者相互相承,微服务是核心, Docker、Devops是工具

5 统一配置中心

介绍Spring Cloud Config组件搭配Spring Cloud Bus, 实现配置自动更新, 集成WebHook

为什么需要统一配置中心?

  • 不方便维护
  • 配置内容安全与权限
  • 更新配置项目需重启

统一配置中心需要一个单独的服务:config-server

5.1 config-server

创建配置中心服务需要的依赖:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-config-server</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.cloud</groupId>
  7. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  8. </dependency>

启动类上注解: @EnableEurekaClient、 @EnableConfigServer

启动后会报错: If you are using the git profile, you need to set a Git URI in your configuration. If you are using a native profile and have spring.cloud.config.server.bootstrap=true, you need to use a composite configuration.

他需要我们配置GIT URI,然后去上面拉取我们的配置, 所以我们需要到GIT上面新建一个项目。

我们这里选用GitHub远程仓库, 创建好仓库后在配置文件中添加如下:

  1. spring:
  2. cloud:
  3. config:
  4. server:
  5. git:
  6. uri: https://github.com/xuesenLi/config-repo
  7. username: 1450002918@qq.com
  8. password: github passworl
  9. # basedir: 将从GIT仓库获取的配置放到指定本地目录

启动项目访问: http://localhost:8080/order-a.yml 即 git上面配置好配置文件。order.yml

我们还可通过访问http://localhost:8080/order-a.properties 、http://localhost:8080/order-a.json来自动转换成properties和json 格式。

配置文件格式:

  • /{name}-{profiles}.yml : 默认 mster分支。

  • /{label}/{name}-{profiles}.yml

name: 服务名

profiles: 环境

label 分支(branch)

5.2 config-client

  1. <!--引入 config-client-->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-config-client</artifactId>
  5. </dependency>

修改配置文件名 : application.yml, bootstrap.yml 表示先启动这个配置文件,然后再从这个配置文件去GIT中获取配置。

  1. spring:
  2. application:
  3. name: order
  4. cloud:
  5. config:
  6. discovery:
  7. enabled: true
  8. service-id: CONFIG #对应config-server 在注册中心的application
  9. profile: dev #表示在git 上面拿到的配置文件名为 order-dev.yml
  10. eureka:
  11. client:
  12. service-url:
  13. defaultZone: http://localhost:8761/eureka/ # 由于当前配置文件最先加载, 我们需要将eureka注册中心地址在这里声明(默认是8761端口号)。不然找不到config服务

config-server高可用

统一配置中心的高可用,分别启动多个实例注册到eureka注册中心,当我们的其他服务调用这个config服务时,就会使用 负载均衡。

5.3 Spring Cloud Bus

使用 SpringCloud Bus(总线)自动更新配置

如何在修改了配置过后config-server, 如何能够通知相应服务

  1. 引入消息队列
  2. 配置接口 /buf-refresh

实操:

5.3.1 引入消息队列

在config-server中引入依赖

  1. <!--spring cloud bus-->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-bus-amqp</artifactId>
  5. </dependency>

由于我是在远程服务器上面启动的RabbitMQ,所以需要到配置文件中配置消息队列地址。 然后启动config-server服务,启动后会为我们自动在RabbitMQ管控台生成队列如下:

同样我们需要在其他服务(order)引入spring cloud bus pom依赖 ,启动服务后,又会为我们自动在RabbitMQ管控台生成队列如下:

队列名是随机生成的, 当我们将相应的服务停掉过后,相应的的队列也会清除掉。

5.3.2 暴露接口 /buf-refresh

在config-server服务配置文件中配置:

  1. management:
  2. endpoints:
  3. web:
  4. exposure:
  5. include: "*" # 暴露所有

当我们在 GIT 中修改相应服务(order)的配置文件后, 发送POST请求http://localhost:8080/actuator/bus-refresh config-server服务端口号为8080, 我们会发现消息队列中会产生相应的记录,并且立马会被消费掉,此时order的配置文件编自动的刷新了 。我们需要到读取配置文件的地方加上注解@RefreshScope//配置文件自动刷新

5.3.3 在git上配置webhooks

Webhooks允许在某些事件发生时通知外部服务。当发生指定事件时,我们将向您提供的每个URL发送一个POST请求。我们只需要将每次修改配置文件PUSH 操作后, 使他自动触发这个POST请求。congfig组件专门为webhooks提供了一个路由接口 monitor

6. 消息和异步

异步

  • 客户端请求不会阻塞进程,服务端的响应可以是非即时的。

异步的常见形态

  • 通知
  • 请求/异步响应
  • 消息

MQ应用场景

  • 异步处理
  • 流量削峰
  • 日志处理(kafka)
  • 应用解耦

6.1 RabbitMQ 基本使用

  1. <!--rabbitMQ -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-amqp</artifactId>
  5. </dependency>

发送MQ消息

  1. /**
  2. *
  3. * 发送mq消息 测试。
  4. * @author Mr.Li
  5. * @date 2020/3/16 - 14:13
  6. */
  7. public class MqSenderTest extends OrderApplicationTests {
  8. @Autowired
  9. private AmqpTemplate amqpTemplate;
  10. @Test
  11. public void sendMQ(){
  12. amqpTemplate.convertAndSend("myQueue", "now : "+ new Date());
  13. }
  14. @Test
  15. public void sendOrder(){
  16. //参数表示: Exchange、 Routing Key、 消息
  17. amqpTemplate.convertAndSend("myOrder","computer", "now : "+ new Date());
  18. }
  19. }

接受MQ消息

  1. @Slf4j
  2. @Component
  3. public class MqReceiver {
  4. //1. @RabbitListener(queues = "myQueue")
  5. //2. 自动创建队列 @RabbitListener(queuesToDeclare = @Queue("myQueue"))
  6. //3. 自动创建, Exchange和Queue绑定
  7. @RabbitListener(bindings = @QueueBinding(
  8. value = @Queue("myQueue"),
  9. exchange = @Exchange("myExchange")
  10. ))
  11. public void process(String message) {
  12. log.info("MqReceiver: {}", message);
  13. }
  14. /**
  15. * 数码供应商服务 接收消息
  16. * @param message
  17. */
  18. @RabbitListener(bindings = @QueueBinding(
  19. exchange = @Exchange("myOrder"),
  20. key = "computer", // Routing Key
  21. value = @Queue("computerOrder")
  22. ))
  23. public void processComputer(String message) {
  24. log.info("computer MqReceiver: {}", message);
  25. }
  26. /**
  27. * 水果供应商服务 接收消息
  28. * @param message
  29. */
  30. @RabbitListener(bindings = @QueueBinding(
  31. exchange = @Exchange("myOrder"),
  32. key = "fruit", //Routing Key
  33. value = @Queue("fruitOrder")
  34. ))
  35. public void processFruit(String message) {
  36. log.info("fruit MqReceiver: {}", message);
  37. }
  38. }

一个 exchange可以绑定多个队列, 通过Routing Key 来区分。 发送消息时,只需要指定Exchange和RoutingKey。 这种情况适用于 : 当服务很大时订单模块分为了:数码供应商服务、水果供应商服务便可以通过绑定Exchange来区分。

6.2 Spring Cloud Stream的使用

他是一个为微服务应用构建消息驱动能力的框架, Stream最大的优势是, 他对消息中间件的进一步封装。能够做到动态的切换中间件。但是目前支持的消息中间只有两种: RabbitMQ, KafKa

下面例子用来整合rabbitMQ:

  1. <!--SpringCloud-stream-rabbit-->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
  5. </dependency>

创建接口:StreamClient

  1. package com.lxs.order.message;
  2. public interface StreamClient {
  3. String INPUT = "myInput";
  4. String OUTPUT = "myOutput";
  5. @Input(StreamClient.INPUT)
  6. SubscribableChannel input();
  7. @Output(StreamClient.OUTPUT)
  8. MessageChannel output();
  9. }

由于当前SpringCloud版本原因,@Input、@OutPut注解里面的值不能重复否则无法启动,所以我们需要在yml配置文件中配置如下:

  1. spring:
  2. cloud:
  3. stream:
  4. bindings:
  5. # mystream:
  6. # group: order # 使消息分组,防止多实例消费。
  7. myInput: # 对应StreamClient.INPUT名称
  8. destination: mystream # 指定输入、输出通道对应的主题名、表示Exchange名:mystream
  9. myOutput: # 对应StreamClient.INPUT名称
  10. destination: mystream

发送消息

  1. package com.lxs.order.controller;
  2. import org.springframework.messaging.support.MessageBuilder;
  3. /**
  4. * 发送消息
  5. * @author Mr.Li
  6. * @date 2020/3/16 - 15:13
  7. */
  8. @RestController
  9. public class SendMessageController {
  10. @Autowired
  11. private StreamClient streamClient;
  12. /**
  13. * 发送 orderDTO对象
  14. */
  15. @GetMapping("/sendMessage")
  16. public void process() {
  17. OrderDTO orderDTO = new OrderDTO();
  18. orderDTO.setOrderId("123456");
  19. streamClient.output().send(MessageBuilder.withPayload(orderDTO).build());
  20. }
  21. }

接受消息

  1. /**
  2. * 消息接收端
  3. */
  4. @Component
  5. @EnableBinding(StreamClient.class) //绑定我们定义的接口
  6. @Slf4j
  7. public class StreamReceiver {
  8. /* @StreamListener(StreamClient.INPUT)
  9. public void process(Object message) {
  10. log.info("-------StreamReceiver: {}", message);
  11. }*/
  12. @StreamListener(StreamClient.INPUT)
  13. public void process(OrderDTO message) {
  14. log.info("-----StreamReceiver: {}", message);
  15. }
  16. }

启动项目后,会自己生成队列,并且绑定Exchange名为mystream, 项目关闭即自动删除

存在问题:当我们同一个服务启动多个实例时,向这个服务发送消息,会出现每个实例都会消费。我们需要在配置文件中配置分组信息。

6.3 在商品和订单服务中使用MQ

docker安装Redis

  1. docker run -d -p 6379:6379 redis:4.0.8

我们在Product服务中减库存后发送MQ消息,消息内容为商品信息

  1. //发送amqp消息
  2. amqpTemplate.convertAndSend("productInfo", JSON.toJSONString(productInfoOutputList));

在订单服务中监听消息队列,并且把减库存后的商品以及剩余库存保存在Redis中

  1. package com.lxs.order.message;
  2. @Component
  3. @Slf4j
  4. public class ProductInfoReceiver {
  5. private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";
  6. @Autowired
  7. private StringRedisTemplate redisTemplate;
  8. @RabbitListener(queuesToDeclare = @Queue("productInfo"))
  9. public void process(String message){
  10. //message => ProductInfoOutput
  11. List<ProductInfoOutput> productInfoOutputList = JSONObject.parseArray(message).toJavaList(ProductInfoOutput.class);
  12. log.info("从队列:{}接收到消息:{}", "productInfo", productInfoOutputList);
  13. //将消息队列中 接收到的消息存储在Redis中,key = productId, value = 库存
  14. for (ProductInfoOutput productInfoOutput : productInfoOutputList) {
  15. redisTemplate.opsForValue()
  16. .set(String.format(PRODUCT_STOCK_TEMPLATE, productInfoOutput.getProductId()),
  17. productInfoOutput.getProductStock().toString());
  18. }
  19. }
  20. }

上面情况中在分布式异步情况下,就会很有可能出现数据不一致的情况。问题:分布式事务, 以及多发消息

改造为:基于消息队列的异步事件驱动

原始流程:

  1. 查询商品信息(调用商品服务)
  2. 计算总价(生成订单详情)
  3. 商品服务扣库存(调用商品服务)
  4. 订单入库(生成订单)

异步扣库存分析:创建订单后发送消息给商品服务扣库存,然后商品服务发送扣库存消息给订单服务,商品和订单服务都变成异步适合秒杀类的场景。

  • 可靠的消息投递
  • 用户体验的变化

实现大致思路:库存需要保存在Redis中,创建订单先读取Redis,库存充足的话,创建订单并发送消息, 减库存并将新值重新设置进Redis中,当我们订单如何出现异常,数据库可以回滚,但是Redis不支持回滚,所以需要我们手动回滚。

如何手动回滚:在订单入库的地方加上try,catch, 一旦抛了异常就把Redis中减去的库存加回去。

总结

本次 利用基于消息队列的异步事件驱动来做解耦异步处理,修改成异步后也要符出相应代价。异步情况下重点的问题就是 数据一致性。

Dubbo + Zookeeper 就是以Zookeeper为注册中心,在CAP理论中保证了C P (数据一致性,分区容错性)而 Euraka设计遵循A P (服务可用性, 分区容错性)。 所以权衡取舍应该遵循具体业务。

7. 服务网关

探讨微服务架构下的服务网关,介绍Spring Cloud Zuul的使用, 路由转发, Cookie处理, 动态路由等Zuul路由相关的功能,以及Zuul的高可用

7.1 服务网关和Zuul

为什么需要网关服务?

每个服务调用的统一入口,所有的请求都通过服务网关。

服务网关的要素:

  • 稳定性, 高可用
  • 性能、并发性
  • 安全性
  • 拓展性

常用的网关方案

  • Nginx + Lua
  • Kong
  • Tyk
  • Spring Cloud Zuul

Zuul的特点

  • 路由 + 过滤器 = Zuul
  • 核心是 一系列的过滤器

Zuul的四种过滤器API

  • 前置(Pre) : 作用 限流、鉴权、参数校验、请求转发
  • 后置(Post)作用 统计、日志
  • 路由(Route)
  • 错误(Error)

7.2 路由转发,排除和自定义

新建网关服务api-gateway

  1. <!-- config-client-->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-config</artifactId>
  5. </dependency>
  6. <!-- eureka-client-->
  7. <dependency>
  8. <groupId>org.springframework.cloud</groupId>
  9. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  10. </dependency>
  11. <!-- 服务网关zuul -->
  12. <dependency>
  13. <groupId>org.springframework.cloud</groupId>
  14. <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-test</artifactId>
  19. <scope>test</scope>
  20. </dependency>

bootstrap.yml

  1. spring:
  2. application:
  3. name: api-gateway
  4. cloud:
  5. config:
  6. discovery:
  7. enabled: true
  8. service-id: CONFIG #对应config-server 在注册中心的application
  9. profile: dev
  10. eureka:
  11. client:
  12. service-url:
  13. defaultZone: http://localhost:8761/eureka/

配置好了过后需要在启动类上面添加注解@EnableZuulProxy。启动项目-Dserver.port=9000

如商品服务的一个接口:http://localhost:8082/product/list

通过网关访问的地址为: http://localhost:9000/product/product/list

如配置服务的一个接口:http://localhost:8080/order-dev.yml

通过网关访问的地址为:http://localhost:9000/config/order-dev.yml

问题:通过服务网关的方式访问报错(type=Gateway Timeout, status=504)

这个错误是应为zuul的默认超时时间比较小,我们配置下zuul的超时时间,因zuul启用了ribbon的负载均衡,还需要设置ribbon的超时时间,注意ribbon的超时时间要小于zuul超时时间 。

7.2.1 配置自定义路由

  1. zuul:
  2. routes: # /myProduct/product/list -> /product/product/list
  3. myProduct: #这个可随便写
  4. path: /myProduct/** #对应自定义路由名称
  5. serviceId: product #服务名
  6. # product: /myProduct/** 简写
  7. #排除某些路由,让其不能访问。
  8. ignored-patterns: #传值为Set
  9. - /product/product/list
  10. - /myProduct/product/list
  11. # - /**/product/list
  12. # spring boot 升为 2.0 后,为了安全,默认 Actuator 只暴露2个端点,heath 和 info
  13. management:
  14. endpoints:
  15. web:
  16. exposure:
  17. include: "*"

配置后访问地址:http://localhost:9000/myProduct/product/list

访问http://localhost:9000/actuator/routes便可查看所有的路由地址。

  1. zuul:
  2. #排除某些路由
  3. ignored-patterns: #传值为Set
  4. - /product/product/list
  5. - /myProduct/product/list
  6. # - /**/product/list

7.3 Cookie和动态路由

  1. // Zuul的配置类
  2. @ConfigurationProperties("zuul")
  3. public class ZuulProperties {
  4. 。。。
  5. private Set<String> sensitiveHeaders = new LinkedHashSet<>(
  6. Arrays.asList("Cookie", "Set-Cookie", "Authorization"));
  7. }

如上默认他会过滤掉Cookie

  1. zuul:
  2. sensitive-headers: #将默认设置为空

完成配置的动态注入

  1. @Component
  2. public class ZuulConfig {
  3. @ConfigurationProperties("zuul")
  4. @RefreshScope
  5. public ZuulProperties zuulProperties(){
  6. return new ZuulProperties();
  7. }
  8. }

7.4 路由和高可用

  • 多个Zuul节点注册到Eureka Server中

建议:

采用Nginx和Zuul “混搭”, 使用Nginx对外暴露一个URL,Nginx把请求转发到多个Zuul服务上,Nginx继续作负载均衡。这边便能做到Nginx和Zuul取长补短。

8. Zuul 的综合使用