0. 学习目标

能够使用Feign进行远程调用 能够搭建Spring Cloud Gateway网关服务 能够配置Spring Cloud Gateway路由过滤器 能够编写Spring Cloud Gateway全局过滤器 能够搭建Spring Cloud Config配置中心服务 能够使用Spring Cloud Bus实时更新配置

1. Feign

在前面的学习中,使用了Ribbon的负载均衡功能,大大简化了远程调用时的代码:

  1. String url = "http://user-service/user/" + id;
  2. User user = this.restTemplate.getForObject(url, User.class)

如果就学到这里,你可能以后需要编写类似的大量重复代码,格式基本相同,无非参数不一样。有没有更优雅的方 式,来对这些代码再次优化呢?
这就是接下来要学的Feign的功能了。

1.1. 简介

Feign也叫伪装:
Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样。你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做。
项目主页:https://github.com/OpenFeign/feign

1.2. 快速入门

1.2.1. 导入依赖

在 consumer-demo 项目的 pom.xml 文件中添加如下依赖

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

Feign的客户端

在 consumer-demo 中编写如下Feign客户端接口类:

  1. package com.itheima.Consumer.client;
  2. import com.itheima.Consumer.client.fallback.UserClientFallback;
  3. import com.itheima.Consumer.config.FeignConfig;
  4. import com.itheima.Consumer.pojo.User;
  5. import org.springframework.cloud.openfeign.FeignClient;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. /**
  9. * @author zhizekai
  10. * @version 1.0
  11. * @date 2022/1/26 11:51
  12. */
  13. @FeignClient("user-service") // 声明当前是一个feign客户端,指定服务名为user-service
  14. public interface UserClient {
  15. @GetMapping("/user/{id}")
  16. User queryById(@PathVariable Long id);
  17. }
  • 首先这是一个接口,Feign会通过动态代理,帮我们生成实现类。这点跟mybatis的mapper很像,
  • @FeignClient声明这是一个Feign客户端,同时通过 value 属性指定服务名称
  • 接口中的定义方法,完全采用SpringMVC的注解,Feign会根据注解帮我们生成URL,并访问获取结果
  • @GetMapping中的/user,请不要忘记;因为Feign需要拼接的是http://user-service/user/{id}

编写新的控制器类 ConsumerFeignController ,使用UserClient访问:

  1. package com.itheima.Consumer.controller;
  2. import com.itheima.Consumer.client.UserClient;
  3. import com.itheima.Consumer.pojo.User;
  4. import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
  5. import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import javax.annotation.Resource;
  12. /**
  13. * @author zhizekai
  14. * @version 1.0
  15. * @date 2022/1/26 11:54
  16. */
  17. @RestController
  18. @RequestMapping("/cf")
  19. @Slf4j
  20. public class ConsumerFeignController {
  21. @Resource
  22. private UserClient userClient;
  23. @GetMapping("/{id}")
  24. public User queryById(@PathVariable Long id) {
  25. return userClient.queryById(id);
  26. }
  27. }

开启Feign功能

在 ConsumerApplication 启动类上,添加注解,开启Feign功能

  1. package com.itheima.Consumer;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.SpringCloudApplication;
  5. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  6. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  7. import org.springframework.cloud.openfeign.EnableFeignClients;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.web.client.RestTemplate;
  10. /**
  11. * @Author zhizekai
  12. * @Date 2022/1/19 19:02
  13. * @Version 1.0
  14. */
  15. @SpringCloudApplication // 组合注解
  16. @EnableFeignClients
  17. public class ConsumerApplication {
  18. public static void main(String[] args) {
  19. SpringApplication.run(ConsumerApplication.class,args);
  20. }
  21. @Bean
  22. @LoadBalanced
  23. public RestTemplate restTemplate() {
  24. return new RestTemplate();
  25. }
  26. }

Feign中已经自动集成了Ribbon负载均衡,因此不需要自己定义RestTemplate进行负载均衡的配置。

1.2.4. 启动测试

访问接口:http://localhost:8080/cf/2

Spring Cloud 02 - 图1

正常获取到了结果。

1.3. 负载均衡

Feign中本身已经集成了Ribbon依赖和自动配置:

Spring Cloud 02 - 图2

因此不需要额外引入依赖,也不需要再注册 RestTemplate 对象。
Fegin内置的ribbon默认设置了请求超时时长,默认是1000,我们可以通过手动配置来修改这个超时时长:

  1. ribbon:
  2. ReadTimeout: 2000 # 读取超时时长
  3. ConnectTimeout: 1000 # 建立链接的超时时长

因为ribbon内部有重试机制,一旦超时,会自动重新发起请求。如果不希望重试,可以添加配置:

修改 添加如下配置:
consumer-demo\src\main\resources\application.yml

  1. ribbon:
  2. ConnectTimeout: 1000 # 连接超时时长
  3. ReadTimeout: 2000 # 数据通信超时时长
  4. MaxAutoRetries: 0 # 当前服务器的重试次数
  5. MaxAutoRetriesNextServer: 0 # 重试多少次服务
  6. OkToRetryOnAllOperations: false # 是否对所有的请求方式都重试

重新给UserService的方法设置上线程沉睡时间2秒可以测试上述配置

1.4. Hystrix支持(了解)

Feign默认也有对Hystrix的集成:

Spring Cloud 02 - 图3

只不过,默认情况下是关闭的。需要通过下面的参数来开启;

修改 添加如下配置:<br />consumer-demo\src\main\resources\application.yml`

  1. feign:
  2. hystrix:
  3. enabled: true

但是,Feign中的Fallback配置不像Ribbon中那样简单了。
1)首先,要定义一个类,实现刚才编写的UserFeignClient,作为fallback的处理类

  1. package com.itheima.Consumer.client.fallback;
  2. import com.itheima.Consumer.client.UserClient;
  3. import com.itheima.Consumer.pojo.User;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * @author zhizekai
  7. * @version 1.0
  8. * @date 2022/1/26 15:10
  9. */
  10. @Component
  11. public class UserClientFallback implements UserClient {
  12. @Override
  13. public User queryById(Long id) {
  14. User user = new User();
  15. user.setId(id);
  16. user.setName("用户异常");
  17. return user;
  18. }
  19. }

2)然后在UserFeignClient中,指定刚才编写的实现类

  1. @FeignClient(value = "user-service", fallback = UserClientFallback.class)
  2. public interface UserClient {
  3. @GetMapping("/user/{id}")
  4. User queryById(@PathVariable("id") Long id);
  5. }

3)重启测试

重启启动 并关闭 user-service 服务,然后在页面访问:http://localhost:8080/cf/8
consumer-demo

Spring Cloud 02 - 图4

1.5. 请求压缩(了解)

Spring Cloud Feign 支持对请求和响应进行GZIP压缩,以减少通信过程中的性能损耗。通过下面的参数即可开启请求 与响应的压缩功能:

  1. feign:
  2. compression:
  3. request:
  4. enabled: true # 开启请求压缩
  5. response:
  6. enabled: true

同时,我们也可以对请求的数据类型,以及触发压缩的大小下限进行设置:

  1. feign:
  2. compression:
  3. request:
  4. enabled: true # 开启请求压缩
  5. mime-types: text/html,application/xml,application/json # 设置压缩的数据类型
  6. min-request-size: 2048 # 设置触发压缩的大小下限
  7. response:
  8. enabled: true

注:上面的数据类型、压缩大小下限均为默认值。

1.6. 日志级别(了解)

前面讲过,通过 logging.level.xx=debug 来设置日志级别。然而这个对Fegin客户端而言不会产生效果。因为 注解修改的客户端在被代理时,都会创建一个新的Fegin.Logger实例。我们需要额外指定这个日志的
@FeignClient
级别才可以。
1)在 consumer-demo 的配置文件中设置com.itheima包下的日志级别都为
debug

修改 添加如下配置:
consumer-demo\src\main\resources\application.yml

  1. logging:
  2. level:
  3. com.itheima: debug

2)在 consumer-demo 编写FeignConfig配置类,定义日志级别

package com.itheima.consumer.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {

@Bean
Logger.Level feignLoggerLevel(){
//记录所有请求和响应的明细,包括头信息、请求体、元数据 return Logger.Level.FULL;
}
}

这里指定的Level级别是FULL,Feign支持4种级别:

NONE:不记录任何日志信息,这是默认值。 BASIC:仅记录请求的方法,URL以及响应状态码和执行时间 HEADERS:在BASIC的基础上,额外记录了请求和响应的头信息 FULL:记录所有请求和响应的明细,包括头信息、请求体、元数据。

3)在 consumer-demo 的 UserClient 接口类上的@FeignClient注解中指定配置类:

package com.itheima.consumer.client;
import import import import import
import
com.itheima.consumer.client.fallback.UserClientFallback; com.itheima.consumer.config.FeignConfig; com.itheima.consumer.pojo.User; org.springframework.cloud.openfeign.FeignClient; org.springframework.web.bind.annotation.GetMapping;
org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = “user-service”, fallback = UserClientFallback.class, configuration = FeignConfig.class)
public interface UserClient {
@GetMapping(“/user/{id}”)
User queryById(@PathVariable Long id);
}

4)重启项目,访问:http://localhost:8080/cf/8;即可看到每次访问的日志:

Spring Cloud 02 - 图5

2. Spring Cloud Gateway网关

2.1. 简介

Spring Cloud Gateway是Spring官网基于Spring 5.0、 Spring Boot 2.0、Project Reactor等技术开发的网关服务。

Spring Cloud Gateway基于Filter链提供网关基本功能:安全、监控/埋点、限流等。 Spring Cloud Gateway为微服务架构提供简单、有效且统一的API路由管理方式。 Spring Cloud Gateway是替代Netflix Zuul的一套解决方案。

Spring Cloud Gateway组件的核心是一系列的过滤器,通过这些过滤器可以将客户端发送的请求转发(路由)到对 应的微服务。 Spring Cloud Gateway是加在整个微服务最前沿的防火墙和代理器,隐藏微服务结点IP端口信息,从 而加强安全保护。Spring Cloud Gateway本身也是一个微服务,需要注册到Eureka服务注册中心。
网关的核心功能是:过滤和路由

Gateway加入后的架构

Spring Cloud 02 - 图6

不管是来自于客户端(PC或移动端)的请求,还是服务内部调用。一切对服务的请求都可经过网关,然后再由 网关来实现 鉴权、动态路由等等操作。Gateway就是我们服务的统一入口。

2.3. 核心概念

路由(route) 路由信息的组成:由一个ID、一个目的URL、一组断言工厂、一组Filter组成。如果路由断言为 真,说明请求URL和配置路由匹配。
断言(Predicate) Spring Cloud Gateway中的断言函数输入类型是Spring 5.0框架中的 ServerWebExchange。Spring Cloud Gateway的断言函数允许开发者去定义匹配来自于Http Request中的任何 信息比如请求头和参数。
过滤器(Filter) 一个标准的Spring WebFilter。 Spring Cloud Gateway中的Filter分为两种类型的Filter,分别 是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理。

2.4. 快速入门

2.4.1. 新建工程

填写基本信息:

Spring Cloud 02 - 图7

Spring Cloud 02 - 图8

打开 文件修改为如下:
heima-springcloud\heima-gateway\pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>heima-springcloud</artifactId>
  7. <groupId>org.itheima</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>heima-gateway</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-starter-gateway</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.cloud</groupId>
  19. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  20. </dependency>
  21. </dependencies>
  22. </project>

2.4.2. 编写启动类

在heima-gateway中创建 com.itheima.gateway.GatewayApplication启动类

  1. package com.itheima.gateway;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  5. @SpringBootApplication
  6. @EnableDiscoveryClient
  7. public class GatewayApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(GatewayApplication.class, args);
  10. }
  11. }

2.4.2. 编写配置

创建 heima-gateway\src\main\resources\application.yml 文件,内容如下:

  1. server:
  2. port: 10010 spring:
  3. application:
  4. name: api-gateway
  5. eureka: client:
  6. service-url:
  7. defaultZone: http://127.0.0.1:10086/eureka instance:
  8. prefer-ip-address: true

2.4.4. 编写路由规则

需要用网关来代理 user-service 服务,先看一下控制面板中的服务状态:

Spring Cloud 02 - 图9
ip为:127.0.0.1
端口为:9091
修改 heima-gateway\src\main\resources\application.yml 文件为:

  1. server:
  2. port: 10010
  3. spring:
  4. application:
  5. name: api-gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. # - id: user-service-route
  10. # # 代理的服务地址
  11. # uri: lb://user-service
  12. # # 路由断言: 可以匹配映射路径
  13. # predicates:
  14. # - Path=/**
  15. # filters:
  16. # - PrefixPath=/user
  17. - id: marburg-route
  18. uri: lb://consumer-demo
  19. predicates:
  20. - Path=/**
  21. filters:
  22. - PrefixPath=/cf
  23. # 默认过滤器对所有路由都生效
  24. default-filters:
  25. - AddResponseHeader=X-Response-Default-MyName, itcast # 添加响应头
  26. # 自定义过滤器
  27. - MyParam=name

原版:

  1. server:
  2. port: 10010
  3. spring:
  4. application:
  5. name: api-gateway
  6. cloud:
  7. gateway:
  8. routes:
  9. # 路由id,可以随意写
  10. - id: user-service-route
  11. # 代理的服务地址
  12. uri: http://127.0.0.1:9091
  13. # 路由断言,可以配置映射路径
  14. predicates:
  15. - Path=/user/**
  16. eureka:
  17. client:
  18. service-url:
  19. defaultZone: http://127.0.0.1:10086/eureka instance:
  20. prefer-ip-address: true

将符合 Path规则的一切请求,都代理到 uri 参数指定的地址
本例中,我们将路径中包含有 /user/** 开头的请求,代理到http://127.0.0.1:9091

2.4.5. 启动测试

访问的路径中需要加上配置规则的映射路径,我们访问:http://localhost:10010/user/8

Spring Cloud 02 - 图10

2.5. 面向服务的路由

在刚才的路由规则中,把路径对应的服务地址写死了!如果同一服务有多个实例的话,这样做显然不合理。 应该根据服务的名称,去Eureka注册中心查找 服务对应的所有实例列表,然后进行动态路由!

2.5.1. 修改映射配置,通过服务名称获取

因为已经配置了Eureka客户端,可以从Eureka获取服务的地址信息。
修改 heima-gateway\src\main\resources\application.yml 文件如下:(还是参考上面的文件)

server:
port: 10010
spring:
application:
name: api-gateway cloud:
gateway:
routes:
#
-
路由id,可以随意写
id: user-service-route
# 代理的服务地址;lb表示从eureka中获取具体服务

21
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:
- Path=/user/**
eureka: client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka instance:
prefer-ip-address: true

路由配置中uri所用的协议为lb时(以uri: lb://user-service为例),gateway将使用 LoadBalancerClient把 user-service通过eureka解析为实际的主机和端口,并进行ribbon负载均衡。

2.5.2. 启动测试

再次启动 ,这次gateway进行代理时,会利用Ribbon进行负载均衡访问:
heima-gateway

http://localhost:10010/user/8
日志中可以看到使用了负载均衡器:

Spring Cloud 02 - 图11

2.6. 路由前缀

2.6.1. 添加前缀

在gateway中可以通过配置路由的过滤器PrefixPath,实现映射路径中地址的添加; 修改 heima-gateway\src\main\resources\application.yml 文件:

1 server:
2 port: 10010

  1. spring:
  2. application:
  3. name: api-gateway

cloud:
gateway: routes:
#
-
路由id,可以随意写
id: user-service-route
# 代理的服务地址;lb表示从eureka中获取具体服务
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:

  • Path=/** filters:

添加请求路径的前缀

  • PrefixPath=/user

eureka: client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka instance:
prefer-ip-address: true

通过PrefixPath=/xxx来指定了路由要添加的前缀。
也就是:

以此类推。

Spring Cloud 02 - 图12

2.6.2. 去除前缀

在gateway中可以通过配置路由的过滤器StripPrefix,实现映射路径中地址的去除;
修改 heima-gateway\src\main\resources\application.yml 文件:

1 server:
2 port: 10010

  1. spring:
  2. application:
  3. name: api-gateway
  4. cloud:
  5. gateway:
  6. routes:

9 # 路由id,可以随意写
10 - id: user-service-route
11 # 代理的服务地址;lb表示从eureka中获取具体服务
12 uri: lb://user-service
13 # 路由断言,可以配置映射路径

  1. predicates:
    • Path=/api/user/**
  2. filters:

17 # 表示过滤1个路径,2表示两个路径,以此类推

    • StripPrefix=1
  1. eureka:
  2. client:
  3. service-url:
  4. defaultZone: http://127.0.0.1:10086/eureka
  5. instance:
  6. prefer-ip-address: true

通过 StripPrefix=1 来指定了路由要去掉的前缀个数。如:路径 /api/user/1 将会被代理到 /user/1 。
也就是:

以此类推。

Spring Cloud 02 - 图13

2.7. 过滤器

2.7.1. 简介

Gateway作为网关的其中一个重要功能,就是实现请求的鉴权。而这个动作往往是通过网关提供的过滤器来实现的。 前面的 路由前缀 章节中的功能也是使用过滤器实现的。

  • Gateway自带过滤器有几十个,常见自带过滤器有: | 过滤器名称 | 说明 | | —- | —- | | AddRequestHeader | 对匹配上的请求加上Header | | AddRequestParameters | 对匹配上的请求路由添加参数 | | AddResponseHeader | 对从网关返回的响应添加Header | | StripPrefix | 对匹配上的请求路径去除前缀 |

Spring Cloud 02 - 图14

详细的说明在官网链接
配置全局默认过滤器

这些自带的过滤器可以和使用 章节中的用法类似,也可以将这些过滤器配置成不只是针对某个路由;而是
路由前缀
可以对所有路由生效,也就是配置默认过滤器:
配置如下:

8
server:
port: 10010 spring:
application:
name: api-gateway cloud:
gateway:
# 默认过滤器,对所有路由生效
default-filters:
# 响应头过滤器,对输出的响应设置其头部属性名称为X-Response-Default-MyName,值为itcast; 如果有多个参数多则重写一行设置不同的参数

  • AddResponseHeader=X-Response-Default-MyName, itcast routes:

路由id,可以随意写

  • id: user-service-route

代理的服务地址;lb表示从eureka中获取具体服务
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:

  • Path=/api/user/** filters:

表示过滤1个路径,2表示两个路径,以此类推

  • StripPrefix=1

上述配置后,再访问 http://localhost:10010/api/user/8 的话;那么可以从其响应中查看到如下信息:

Spring Cloud 02 - 图15

过滤器类型:Gateway实现方式上,有两种过滤器;

  1. 局部过滤器:通过 spring.cloud.gateway.routes.filters 配置在具体路由下,只作用在当前路由 上;自带的过滤器都可以配置或者自定义按照自带过滤器的方式。如果配置 spring.cloud.gateway.default-filters上会对所有路由生效也算是全局的过滤器;但是这些过滤器 的实现上都是要实现GatewayFilterFactory接口。
  2. 全局过滤器:不需要在配置文件中配置,作用在所有的路由上;实现 GlobalFilter接口即可。

    2.7.2. 执行生命周期

    Spring Cloud Gateway 的 Filter 的生命周期也类似Spring MVC的拦截器有两个:“pre” 和 “post”。“pre”和 “post” 分 别会在请求被执行前调用和被执行后调用。

Spring Cloud 02 - 图16

这里的pre和post可以通过过滤器的 GatewayFilterChain 执行filter方法前后来实现。

2.7.3. 使用场景

常见的应用场景如下:

  • 请求鉴权:一般 GatewayFilterChain 执行filter方法前,如果发现没有访问权限,直接就返回空。
  • 异常处理:一般 GatewayFilterChain 执行filter方法后,记录异常并返回。
  • 服务调用时长统计: GatewayFilterChain 执行filter方法前后根据时间统计。

    2.8. 自定义过滤器

    2.8.1. 自定义局部过滤器

    需求:在application.yml中对某个路由配置过滤器,该过滤器可以在控制台输出配置文件中指定名称的请求参数的值。
    该过滤器只作用于在yml配置文件中routes 中配置的路由,作用域受spring.cloud.gateway.routes.uri 控制。

    1)编写过滤器

    在heima-gateway工程编写过滤器工厂类MyParamGatewayFilterFactory ```java package com.itheima.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component;

import java.util.Arrays; import java.util.List;

/**

  • @author zhizekai
  • @version 1.0
  • @date 2022/1/27 18:03 */

@Component public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory {

  1. static final String PARAM_NAME = "param";
  2. public MyParamGatewayFilterFactory() {
  3. super(Config.class);
  4. }
  5. public List<String> shortcutFieldOrder() {
  6. return Arrays.asList(PARAM_NAME);
  7. }
  8. @Override
  9. public GatewayFilter apply(Config config) {
  10. return (exchange, chain) -> {
  11. // http://localhost:10010/api/user/8?name=itcast config.param ==> name
  12. //获取请求参数中param对应的参数名 的参数值
  13. ServerHttpRequest request = exchange.getRequest();
  14. if(request.getQueryParams().containsKey(config.param)){
  15. request.getQueryParams().get(config.param).
  16. forEach(value -> System.out.printf("------------局部过滤器--------%s = %s------", config.param, value));
  17. }
  18. return chain.filter(exchange);
  19. };
  20. }
  21. public static class Config{
  22. //对应在配置过滤器的时候指定的参数名
  23. private String param;
  24. public String getParam() {
  25. return param;
  26. }
  27. public void setParam(String param) {
  28. this.param = param;
  29. }
  30. }

}

  1. <a name="yBoWS"></a>
  2. #### 2)修改配置文件
  3. 在heima-gateway工程修改 `heima-gateway\src\main\resources\application.yml` 配置文件
  4. ```yaml
  5. server:
  6. port: 10010
  7. spring:
  8. application:
  9. name: api-gateway
  10. cloud:
  11. gateway:
  12. routes:
  13. # - id: user-service-route
  14. # # 代理的服务地址
  15. # uri: lb://user-service
  16. # # 路由断言: 可以匹配映射路径
  17. # predicates:
  18. # - Path=/**
  19. # filters:
  20. # - PrefixPath=/user
  21. - id: marburg-route
  22. uri: lb://consumer-demo
  23. predicates:
  24. - Path=/**
  25. filters:
  26. - PrefixPath=/cf
  27. # 默认过滤器对所有路由都生效
  28. default-filters:
  29. - AddResponseHeader=X-Response-Default-MyName, itcast # 添加响应头
  30. # 自定义过滤器
  31. - MyParam=name
  32. eureka:
  33. client:
  34. service-url:
  35. defaultZone: http://127.0.0.1:10086/eureka
  36. instance:
  37. prefer-ip-address: true

注意:自定义过滤器的命名应该为:*GatewayFilterFactory

测试访问:http://localhost:10010/api/user/8?name=itcast 检查后台是否输出name和itcast;但是若访问 http://localhost:10010/api/user/8?name2=itcast 则是不会输出的。

2.8.2. 自定义全局过滤器

需求:模拟一个登录的校验。基本逻辑:如果请求中有token参数,则认为请求有效,放行。 在heima-gateway工程编写全局过滤器类MyGlobalFilter

package com.itheima.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zhizekai
 * @version 1.0
 * @date 2022/1/27 18:15
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("--------------全局过滤器MyGlobalFilter------------------");
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if(StringUtils.isBlank(token)){
            //设置响应状态码为未授权
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }else {
            System.out.println("token : " + token);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //值越小越先执行
        return 1;
    }
}

访问 http://localhost:10010/api/user/8

Spring Cloud 02 - 图17

访问 http://localhost:10010/api/user/8?token=abc

Spring Cloud 02 - 图18

2.9. 负载均衡和熔断(了解)

Gateway中默认就已经集成了Ribbon负载均衡和Hystrix熔断机制。但是所有的超时策略都是走的默认值,比如熔断 超时时间只有1S,很容易就触发了。因此建议手动进行配置:

  1. hystrix:
  2. command:
  3. default:
  4. execution:
  5. isolation:
  6. thread:
  7. timeoutInMilliseconds: 6000
  8. ribbon:
  9. ConnectTimeout: 1000
  10. ReadTimeout: 2000
  11. MaxAutoRetries: 0
  12. MaxAutoRetriesNextServer: 0

2.10. Gateway跨域配置

一般网关都是所有微服务的统一入口,必然在被调用的时候会出现跨域问题。
跨域:在js请求访问中,如果访问的地址与当前服务器的域名、ip或者端口号不一致则称为跨域请求。若不解决则不 能获取到对应地址的返回结果。
如:从在http://localhost:9090中的js访问 http://localhost:9000的数据,因为端口不同,所以也是跨域请求。
在访问Spring Cloud Gateway网关服务器的时候,出现跨域问题的话;可以在网关服务器中通过配置解决,允许哪 些服务是可以跨域请求的;具体配置如下:

  1. spring:
  2. cloud:
  3. gateway:
  4. globalcors:
  5. corsConfigurations: 6 ‘[/**]’:

7 #allowedOrigins: # 这种写法或者下面的都可以,表示全部

  1. allowedOrigins:
  2. allowedMethods:
    • GET

上述配置表示:可以允许来自 http://docs.spring.io 的get请求方式获取服务数据。
allowedOrigins 指定允许访问的服务器地址,如:http://localhost:10000 也是可以的。
‘[/**]’ 表示对所有访问到网关服务器的请求地址
官网具体说明:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.1.1.RELEASE/multi/mul ti cors_configuration.html

2.11. Gateway的高可用(了解)

启动多个Gateway服务,自动注册到Eureka,形成集群。如果是服务内部访问,访问Gateway,自动负载均衡,没问题。
但是,Gateway更多是外部访问,PC端、移动端等。它们无法通过Eureka进行负载均衡,那么该怎么办? 此时,可以使用其它的服务网关,来对Gateway进行代理。比如:Nginx

2.12. Gateway与Feign的区别

Gateway 作为整个应用的流量入口,接收所有的请求,如PC、移动端等,并且将不同的请求转发至不同的处理 微服务模块,其作用可视为nginx;大部分情况下用作权限鉴定、服务端流量控制
Feign则是将当前微服务的部分服务接口暴露出来,并且主要用于各个微服务之间的服务调用

3. Spring Cloud Config分布式配置中心

3.1. 简介

在分布式系统中,由于服务数量非常多,配置文件分散在不同的微服务项目中,管理不方便。为了方便配置文件集中 管理,需要分布式配置中心组件。在Spring Cloud中,提供了Spring Cloud Config,它支持配置文件放在配置服务 的本地,也支持放在远程Git仓库(GitHub、码云)。
使用Spring Cloud Config配置中心后的架构如下图:

Spring Cloud 02 - 图19

配置中心本质上也是一个微服务,同样需要注册到Eureka服务注册中心!

3.2. Git配置管理

3.2.1. 远程Git仓库

知名的Git远程仓库有国外的GitHub和国内的码云(gitee);但是使用GitHub时,国内的用户经常遇到的问题是访 问速度太慢,有时候还会出现无法连接的情况。如果希望体验更好一些,可以使用国内的Git托管服务——码云
(gitee.com)。
与GitHub相比,码云也提供免费的Git仓库。此外,还集成了代码质量检测、项目演示等功能。对于团队协作开发, 码云还提供了项目管理、代码托管、文档管理的服务。本章中使用的远程Git仓库是码云。
码云访问地址:https://gitee.com/

3.2.2. 创建远程仓库

首先要使用码云上的私有远程git仓库需要先注册帐号;请先自行访问网站并注册帐号,然后使用帐号登录码云控制台 并创建公开仓库。

Spring Cloud 02 - 图20

Spring Cloud 02 - 图21

3.2.3. 创建配置文件

在新建的仓库中创建需要被统一配置管理的配置文件。 配置文件的命名方式:{application}-{profile}.yml 或 {application}-{profile}.properties application为应用名称
profile用于区分开发环境,测试环境、生产环境等
如user-dev.yml,表示用户微服务开发环境下使用的配置文件。
这里将user-service工程的配置文件application.yml文件的内容复制作为user-dev.yml文件的内容,具体配置如下:

Spring Cloud 02 - 图22

创建 ;内容来自 user-service\src\main\resources\application.yml (方便后面测试user-
user-dev.yml service项目的配置),可以如下:

server:
port: ${port:9091} spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springcloud username: root
password: root application:
#应用名
name: user-service mybatis:
type-aliases-package: com.itheima.user.pojo eureka:
client: service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:

ip-address: 127.0.0.1
prefer-ip-address: true
lease-expiration-duration-in-seconds: 90
lease-renewal-interval-in-seconds: 30

Spring Cloud 02 - 图23

创建完user-dev.yml配置文件之后,gitee中的仓库如下:

Spring Cloud 02 - 图24

3.3. 搭建配置中心微服务

3.3.1. 创建工程

创建配置中心微服务工程:

Spring Cloud 02 - 图25

Spring Cloud 02 - 图26

添加依赖,修改 config-server\pom.xml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>heima-springcloud</artifactId>
        <groupId>org.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>config-server</artifactId>


    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
        <!--spring cloud buys 相关服务-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-bus</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
        </dependency>
    </dependencies>

</project>

3.3.2. 启动类

创建配置中心工程 config-server 的启动类;

如下:
config-server\src\main\java\com\itheima\config\ConfigServerApplication.java

package com.itheima.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication { public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}

3.3.3. 配置文件

创建配置中心工程 config-server 的配置文件;

如下:
config-server\src\main\resources\application.yml

1 server:
2 port: 12000

  1. spring:
  2. application:
  3. name: config-server
  4. cloud:
  5. config:
  6. server:
  7. git:
  8. uri: https://gitee.com/liaojianbin/heima-config.git
  9. eureka:
  10. client:
  11. service-url:
  12. defaultZone: http://127.0.0.1:10086/eureka 15

注意上述的 spring.cloud.config.server.git.uri 则是在码云创建的仓库地址;可修改为你自己创建的仓库地址

3.3.4. 启动测试

启动eureka注册中心和配置中心;然后访问http://localhost:12000/user-dev.yml ,查看能否输出在码云存储管理的
user-dev.yml文件。并且可以在gitee上修改user-dev.yml然后刷新上述测试地址也能及时到最新数据。

Spring Cloud 02 - 图27

3.4. 获取配置中心配置

前面已经完成了配置中心微服务的搭建,下面我们就需要改造一下用户微服务 user-service ,配置文件信息不再由 微服务项目提供,而是从配置中心获取。如下对 user-service 工程进行改造。

3.4.1. 添加依赖

在 user-service 工程中的pom.xml文件中添加如下依赖:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
  <version>2.1.1.RELEASE</version>
</dependency>

3.4.2. 修改配置

  1. 删除 user-service 工程的 user-service\src\main\resources\application.yml 文件(因为该文件从配置 中心获取)
  2. 创建 user-service 工程 user-service\src\main\resources\bootstrap.yml 配置文件

spring: cloud:
config:
# 与远程仓库中的配置文件的application保持一致
name: user
# 远程仓库中的配置文件的profile保持一致
profile: dev
# 远程仓库中的版本保持一致
label: master discovery:
# 使用配置中心
enabled: true
# 配置中心服务id
service-id: config-server
eureka: client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka

工程修改后结构:
user-service

Spring Cloud 02 - 图28

bootstrap.yml文件也是Spring Boot的默认配置文件,而且其加载的时间相比于application.yml更早。 application.yml和bootstrap.yml虽然都是Spring Boot的默认配置文件,但是定位却不相同。bootstrap.yml
可以理解成系统级别的一些参数配置,这些参数一般是不会变动的。application.yml 可以用来定义应用级别的
参数,如果搭配 spring cloud config 使用,application.yml 里面定义的文件可以实现动态替换。
总结就是,bootstrap.yml文件相当于项目启动时的引导文件,内容相对固定。application.yml文件是微服务 的一些常规配置参数,变化比较频繁。

3.4.3. 启动测试

启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service ,如果启动没有报错其实已经 使用上配置中心内容,可以到注册中心查看,也可以检验 user-service 的服务。

Spring Cloud 02 - 图29

4. Spring Cloud Bus服务总线

4.1. 问题

前面已经完成了将微服务中的配置文件集中存储在远程Git仓库,并且通过配置中心微服务从Git仓库拉取配置文件, 当用户微服务启动时会连接配置中心获取配置信息从而启动用户微服务。
如果我们更新Git仓库中的配置文件,那用户微服务是否可以及时接收到新的配置信息并更新呢?

4.1.1. 修改远程Git配置

修改在码云上的user-dev.yml文件,添加一个属性test.name。

Spring Cloud 02 - 图30

4.1.2. 修改UserController

修改 user-service 工程中的处理器类;

user-service\src\main\java\com\itheima\user\controller\UserController.java 如下:

1 package com.itheima.user.controller;
2
3 import com.itheima.user.pojo.User;
4 import com.itheima.user.service.UserService;
5 import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.beans.factory.annotation.Value;
7 import org.springframework.web.bind.annotation.GetMapping;
8 import org.springframework.web.bind.annotation.PathVariable;
9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.RestController;
11
12 @RestController
13 @RequestMapping(“/user”)
14 public class UserController {
15
16 } @Autowired
private UserService userService;
@Value(“${test.name}”) private String name;
@GetMapping(“/{id}”)
public User queryById(@PathVariable Long id){ System.out.println(“配置文件中的test.name = “ + name); return userService.queryById(id);
}
17
18
19
20
21
22
23
24
25
26
27

4.1.3. 测试

依次启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service ;然后修改Git仓库中的配 置信息,访问用户微服务,查看输出内容。

结论:通过查看用户微服务控制台的输出结果可以发现,我们对于Git仓库中配置文件的修改并没有及时更新到用户 微服务,只有重启用户微服务才能生效。
如果想在不重启微服务的情况下更新配置该如何实现呢? 可以使用Spring Cloud Bus来实现配置的自动更新。

需要注意的是Spring Cloud Bus底层是基于RabbitMQ实现的,默认使用本地的消息队列服务,所以需要提前 启动本地RabbitMQ服务(安装RabbitMQ以后才有),如下:

Spring Cloud 02 - 图31

Spring Cloud Bus简介

Spring Cloud Bus是用轻量的消息代理将分布式的节点连接起来,可以用于广播配置文件的更改或者服务的监控管 理。也就是消息总线可以为微服务做监控,也可以实现应用程序之间相互通信。 Spring Cloud Bus可选的消息代理 有RabbitMQ和Kafka。

使用了Bus之后:

Spring Cloud 02 - 图32

4.3. 改造配置中心

  1. 在 config-server 项目的pom.xml文件中加入Spring Cloud Bus相关依赖

1
2
3
4
5
6
7
8
9

org.springframework.cloud
spring-cloud-bus


org.springframework.cloud
spring-cloud-stream-binder-rabbit

  1. 在 config-server 项目修改application.yml文件如下:

9
10
11
server:
port: 12000 spring:
application:
name: config-server cloud:
config: server:
git:
uri: https://gitee.com/liaojianbin/heima-config.git
# rabbitmq的配置信息;如下配置的rabbit都是默认值,其实可以完全不配置

25
26
27
rabbitmq:
host: localhost port: 5672 username: guest password: guest
eureka: client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka management:
endpoints: web:
exposure:
# 暴露触发消息总线的地址
include: bus-refresh

4.4. 改造用户服务

在用户微服务 user-service 项目的pom.xml中加入Spring Cloud Bus相关依赖

9
10
11
12

org.springframework.cloud
spring-cloud-bus


org.springframework.cloud
spring-cloud-stream-binder-rabbit


org.springframework.boot
spring-boot-starter-actuator

  1. 修改 user-service 项目的bootstrap.yml如下:

11
12
spring: cloud:
config:
# 与远程仓库中的配置文件的application保持一致
name: user
# 远程仓库中的配置文件的profile保持一致
profile: dev
# 远程仓库中的版本保持一致 label: master discovery:
# 使用配置中心
enabled: true

13
14
# 配置中心服务id
service-id: config-server
# rabbitmq的配置信息;如下配置的rabbit都是默认值,其实可以完全不配置 rabbitmq:
host: localhost port: 5672 username: guest password: guest
eureka: client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka

  1. 改造用户微服务 user-service 项目的UserController

Spring Cloud 02 - 图33

4.5. 测试

前面已经完成了配置中心微服务和用户微服务的改造,下面来测试一下,当我们修改了Git仓库中的配置文件,用户 微服务是否能够在不重启的情况下自动更新配置信息。

测试步骤:

第一步:依次启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service
第二步:访问用户微服务http://localhost:9091/user/8;查看IDEA控制台输出结果
第三步:修改Git仓库中配置文件 user-dev.yml 的 test.name 内容
第四步:使用Postman或者RESTClient工具发送POST方式请求访问地址http://127.0.0.1:12000/actuator/bus-refre sh

Spring Cloud 02 - 图34
第五步:访问用户微服务系统控制台查看输出结果 说明
1、Postman或者RESTClient是一个可以模拟浏览器发送各种请求(POST、GET、PUT、DELETE等)的工具
2、请求地址http://127.0.0.1:12000/actuator/bus-refresh中 /actuator是固定的,/bus-refresh对应的是配置 中心config-server中的application.yml文件的配置项include的内容
3、请求http://127.0.0.1:12000/actuator/bus-refresh地址的作用是访问配置中心的消息总线服务,消息总线 服务接收到请求后会向消息队列中发送消息,各个微服务会监听消息队列。当微服务接收到队列中的消息后, 会重新从配置中心获取最新的配置信息。

4.6. Spring Cloud 体系技术综合应用概览

Spring Cloud 02 - 图35