Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线

学习目标

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

Feign

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

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

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

这就是接下来要学的Feign的功能了。

简介

Feign也叫伪装:

Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样。你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做。

项目主页:https://github.com/OpenFeign/feign
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第1张图片

快速入门

导入依赖

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

<dependency>
	<groupId>org.springframework.cloudgroupId>
	<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
Feign 的客户端

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

package com.itheima.consumer.client;

import com.itheima.consumer.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

// 声明当前是一个Feign客户端,指定服务名为user-service
@FeignClient("user-service")
@Component("userClient")
public interface UserClient {

    // http://user-service/user/12
    @GetMapping("/user/{id}")
    public User queryById(@PathVariable(value = "id") Long id);
}
  • 首先这是一个接口,Feign会通过动态代理,帮我们生成实现类。这点跟mybatis的mapper很像
  • @FeignClient ,声明这是一个Feign客户端,同时通过 value 属性指定服务名称
  • 接口中的定义方法,完全采用SpringMVC的注解,Feign会根据注解帮我们生成URL,并访问获取结果
  • @GetMapping中的/user,请不要忘记;因为Feign需要拼接可访问的地址

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

package com.itheima.consumer.controller;

import com.itheima.consumer.client.UserClient;
import com.itheima.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cf")
public class ConsumerFeignController {

    @Autowired
    private UserClient userClient;

    @GetMapping("/{id}")
    public User queryById(@PathVariable(value = "id") Long id) {
        return userClient.queryById(id);
    }
}
开启 Feign 功能

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

package com.itheima.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/*@SpringBootApplication
@EnableDiscoveryClient  // 开启Eureka客户端发现功能
@EnableCircuitBreaker // 开启熔断*/
@SpringCloudApplication
@EnableFeignClients // 开启Feign功能
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

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

启动测试

访问接口:http://localhost:8080/cf/2
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第2张图片
正常获取到了结果。

负载均衡

Feign中本身已经集成了Ribbon依赖和自动配置:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第3张图片
因此不需要额外引入依赖,也不需要再注册 RestTemplate 对象。

Fegin内置的ribbon默认设置了请求超时时长,默认是1000,我们可以通过手动配置来修改这个超时时长:

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

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

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

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

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

Hystrix支持(了解)

Feign默认也有对Hystrix的集成:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第4张图片
只不过,默认情况下是关闭的。需要通过下面的参数来开启;

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

feign:
  hystrix:
    enabled: true # 开启Feign的熔断功能

但是,Feign中的Fallback配置不像Ribbon中那样简单了。

1)首先,要定义一个类,实现刚才编写的UserClient接口,作为fallback的处理类

package com.itheima.consumer.client.fallback;

import com.itheima.consumer.client.UserClient;
import com.itheima.consumer.pojo.User;
import org.springframework.stereotype.Component;

@Component
public class UserClientFallback implements UserClient {
    @Override
    public User queryById(Long id) {
        User user = new User();
        user.setId(id);
        user.setName("用户异常");
        return user;
    }
}

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

package com.itheima.consumer.client;

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

// 声明当前是一个Feign客户端,指定服务名为user-service
@FeignClient(value = "user-service", fallback = UserClientFallback.class)
@Component("userClient")
public interface UserClient {

    // http://user-service/user/12
    @GetMapping("/user/{id}")
    public User queryById(@PathVariable(value = "id") Long id);
}

3)重启测试

重启启动consumer-demo并关闭user-service服务,然后在页面访问:http://localhost:8080/cf/8
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第5张图片

请求压缩(了解)

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

feign:
  compression:
      request:
        enabled: true # 开启请求压缩
      response:
        enabled: true # 开启响应压缩

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

feign:
  compression:
      request:
        enabled: true # 开启请求压缩
        mime-types: text/html,application/xml,application/json # 设置压缩的数据类型
        min-request-size: 2048 # 设置触发压缩的大小下限
      response:
        enabled: true # 开启响应压缩

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

日志级别(了解)

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

1)在 consumer-demo 的配置文件中设置com.itheima包下的日志级别都为 debug

logging:
  level:
    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级别是FULLFeign支持4种级别:

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

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

package com.itheima.consumer.client;

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

// 声明当前是一个Feign客户端,指定服务名为user-service
@FeignClient(value = "user-service", fallback = UserClientFallback.class, configuration = FeignConfig.class)
@Component("userClient")
public interface UserClient {

    // http://user-service/user/12
    @GetMapping("/user/{id}")
    public User queryById(@PathVariable(value = "id") Long id);
}

4)重启项目,访问:http://localhost:8080/cf/8 ;即可看到每次访问的日志:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第6张图片

Spring Cloud Gateway 网关

简介

  • 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 Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第7张图片
不管是来自于客户端(PC或移动端)的请求,还是服务内部调用。一切对服务的请求都可经过网关,然后再由网关来实现 鉴权、动态路由等等操作。Gateway就是我们服务的统一入口。

核心概念

① 路由(route)

路由信息的组成:由一个ID、一个目的URL、一组断言工厂、一组Filter组成。如果路由断言为真,说明请求URL和配置路由匹配。

② 断言(Predicate)

Spring Cloud Gateway中的断言函数输入类型是Spring 5.0框架中的ServerWebExchangeSpring Cloud Gateway的断言函数允许开发者去定义匹配来自于Http Request中的任何信息比如请求头和参数。

③ 过滤器(Filter)

一个标准的Spring WebFilterSpring Cloud Gateway中的Filter分为两种类型的Filter,分别是Gateway FilterGlobal Filter。过滤器Filter将会对请求和响应进行修改处理。

快速入门

新建工程

填写基本信息:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第8张图片
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第9张图片
打开 heima-springcloud\heima-gateway\pom.xml 文件修改为如下:


<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-springcloudartifactId>
        <groupId>com.itheimagroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <groupId>com.itheimagroupId>
    <artifactId>heima-gatewayartifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-gatewayartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
    dependencies>

project>
编写启动类

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

package com.itheima.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}
编写配置

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

server:
  port: 10010
spring:
  application:
    name: api-gateway
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    prefer-ip-address: true
编写路由规则

需要用网关来代理 user-service 服务,先看一下Spring监控面板中的服务状态:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第10张图片

  • ip为:127.0.0.1
  • 端口为:9091

修改 heima-gateway\src\main\resources\application.yml 文件为:

server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # 路由id,可以随意写
        - id: user-service-route
          # 代理的服务地址
          uri: http://127.0.0.1:9091
          # # 路由断言: 可以匹配映射路径
          predicates:
            - Path=/user/**
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    prefer-ip-address: true

将符合 Path 规则的一切请求,都代理到 uri 参数指定的地址

本例中,我们将路径中包含有 /user/** 开头的请求,代理到http://127.0.0.1:9091

启动测试

访问的路径中需要加上配置规则的映射路径,我们访问:http://localhost:10010/user/8
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第11张图片

面向服务的路由

在刚才的路由规则中,把路径对应的服务地址写死了!如果同一服务有多个实例的话,这样做显然不合理。

应该根据服务的名称,去Eureka注册中心查找 服务对应的所有实例列表,然后进行动态路由!

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

因为已经配置了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中获取具体服务
          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将使用 LoadBalancerClientuser-service通过eureka解析为实际的主机和端口,并进行ribbon负载均衡。

启动测试

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

http://localhost:10010/user/8

日志中可以看到使用了负载均衡器:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第12张图片

路由前缀

添加前缀

gateway中可以通过配置路由的过滤器PrefixPath,实现映射路径中地址的添加;

修改 heima-gateway\src\main\resources\application.yml 文件:

server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # 路由id,可以随意写
        - id: user-service-route
          # 代理的服务地址
          #uri: http://127.0.0.1:9091
          # lb 表示从Eureka中获取具体服务
          uri: lb://user-service
          # # 路由断言: 可以匹配映射路径
          predicates:
            #- Path=/user/**
            - Path=/**
          filters:
            # 添加请求路径的前缀
            - PrefixPath=/user

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

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

也就是:

  • PrefixPath=/user http://localhost:10010/8 --》 http://localhost:9091/user/8
  • PrefixPath=/user/abc http://localhost:10010/8 --》 http://localhost:9091/user/abc/8

以此类推。
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第13张图片

去除前缀

gateway中可以通过配置路由的过滤器StripPrefix,实现映射路径中地址的去除;

修改 heima-gateway\src\main\resources\application.yml 文件:

server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # 路由id,可以随意写
        - id: user-service-route
          # 代理的服务地址
          #uri: http://127.0.0.1:9091
          # lb 表示从Eureka中获取具体服务
          uri: lb://user-service
          # # 路由断言: 可以匹配映射路径
          predicates:
            #- Path=/user/**
            #- Path=/**
            - Path=/api/user/**
          filters:
            # 添加请求路径的前缀
            #- PrefixPath=/user
            # 1表示过滤1个路径,2表示两个路径,以此类推
            - StripPrefix=1

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

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

也就是:

  • StripPrefix=1 http://localhost:10010/api/user/8 --》http://localhost:9091/user/8
  • StripPrefix=2 http://localhost:10010/api/user/8 --》http://localhost:9091/8

以此类推。
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第14张图片

过滤器

简介

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

Gateway自带过滤器有几十个,常见自带过滤器有:

过滤器名称 说明
AddRequestHeader 对匹配上的请求加上Header
AddRequestParameters 对匹配上的请求路由添加参数
AddResponseHeader 对从网关返回的响应添加Header
StripPrefix 对匹配上的请求路径去除前缀

Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第15张图片
详细的说明在官网链接

配置全局默认过滤器

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

server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # 路由id,可以随意写
        - id: user-service-route
          # 代理的服务地址
          #uri: http://127.0.0.1:9091
          # lb 表示从Eureka中获取具体服务
          uri: lb://user-service
          # # 路由断言: 可以匹配映射路径
          predicates:
            #- Path=/user/**
            #- Path=/**
            - Path=/api/user/**
          filters:
            # 添加请求路径的前缀
            #- PrefixPath=/user
            # 1表示过滤1个路径,2表示两个路径,以此类推
            - StripPrefix=1
      # 默认过滤器,对所有路由都生效
      default-filters:
        # 响应头过滤器,对输出的响应设置其头部属性名称为X-Response-Default-MyName,值为itcast;如果有多个参数多则重写一行设置不同的参数
        - AddResponseHeader=X-Response-Foo, Bar
        - AddResponseHeader=abc-myname,heima

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

上述配置后,再访问 http://localhost:10010/api/user/8 的话;那么可以从其响应中查看到如下信息:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第16张图片

过滤器类型

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

  • 局部过滤器

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

  • 全局过滤器

不需要在配置文件中配置,作用在所有的路由上;实现 GlobalFilter 接口即可。

执行生命周期

Spring Cloud GatewayFilter 的生命周期也类似Spring MVC的拦截器有两个:“pre” 和 “post”。“pre”和 “post” 分别会在请求被执行前调用和被执行后调用。
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第17张图片
这里的 prepost 可以通过过滤器的 GatewayFilterChain 执行filter方法前后来实现。

使用场景

常见的应用场景如下:

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

自定义过滤器

自定义局部过滤器

需求:在application.yml中对某个路由配置过滤器,该过滤器可以在控制台输出配置文件中指定名称的请求参数的值。

编写过滤器

heima-gateway工程编写过滤器工厂类MyParamGatewayFilterFactory

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;

@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {

    static final String PARAM_NAME = "param";

    public MyParamGatewayFilterFactory() {
        super(Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM_NAME);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // http://localhost:10010/api/user/8?name=itcast   config.param ==> name
            //获取请求参数中param对应的参数名 的参数值
            ServerHttpRequest request = exchange.getRequest();
            if (request.getQueryParams().containsKey(config.param)) {
                request.getQueryParams().get(config.param).
                        forEach(value -> System.out.printf("------------局部过滤器--------%s = %s------", config.param, value));
            }
            return chain.filter(exchange);
        };
    }

    public static class Config {
        //对应在配置过滤器的时候指定的参数名
        private String param;

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }
}
修改配置文件

heima-gateway工程修改 heima-gateway\src\main\resources\application.yml 配置文件

server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # 路由id,可以随意写
        - id: user-service-route
          # 代理的服务地址
          #uri: http://127.0.0.1:9091
          # lb 表示从Eureka中获取具体服务
          uri: lb://user-service
          # # 路由断言: 可以匹配映射路径
          predicates:
            #- Path=/user/**
            #- Path=/**
            - Path=/api/user/**
          filters:
            # 添加请求路径的前缀
            #- PrefixPath=/user
            # 1表示过滤1个路径,2表示两个路径,以此类推
            - StripPrefix=1
            # 自定义过滤器
            - MyParam=name
      # 默认过滤器,对所有路由都生效
      default-filters:
        # 响应头过滤器,对输出的响应设置其头部属性名称为X-Response-Default-MyName,值为itcast;如果有多个参数多则重写一行设置不同的参数
        - AddResponseHeader=X-Response-Foo, Bar
        - AddResponseHeader=abc-myname, heima

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

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

测试访问:http://localhost:10010/api/user/8?name=itcast 检查后台是否输出name和itcast;

但是若访问:http://localhost:10010/api/user/8?name2=itcast 则是不会输出的。

自定义全局过滤器

需求:模拟一个登录的校验。基本逻辑:如果请求中有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;

@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();
        }
        return chain.filter(exchange);
    }

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

访问 http://localhost:10010/api/user/8
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第18张图片
访问 http://localhost:10010/api/user/8?token=abc
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第19张图片

负载均衡和熔断(了解)

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

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000

ribbon:
  ConnectTimeout: 1000
  ReadTimeout: 2000
  MaxAutoRetries: 0
  MaxAutoRetriesNextServer: 0

Gateway跨域配置

一般网关都是所有微服务的统一入口,必然在被调用的时候会出现跨域问题。

跨域:在js请求访问中,如果访问的地址与当前服务器的域名、ip或者端口号不一致则称为跨域请求。若不解决则不能获取到对应地址的返回结果。

如:从在http://localhost:9090中的js访问 http://localhost:9000的数据,因为端口不同,所以也是跨域请求。

在访问Spring Cloud Gateway网关服务器的时候,出现跨域问题的话;可以在网关服务器中通过配置解决,允许哪些服务是可以跨域请求的;具体配置如下:

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            #allowedOrigins: * # 这种写法或者下面的都可以,*表示全部
            allowedOrigins:
              - "http://docs.spring.io"
            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/multi__cors_configuration.html

Gateway的高可用(了解)

启动多个Gateway服务,自动注册到Eureka,形成集群。如果是服务内部访问,访问Gateway,自动负载均衡,没问题。

但是,Gateway更多是外部访问,PC端、移动端等。它们无法通过Eureka进行负载均衡,那么该怎么办?

此时,可以使用其它的服务网关,来对Gateway进行代理。比如:Nginx

Gateway与Feign的区别

Gateway 作为整个应用的流量入口,接收所有的请求,如PC、移动端等,并且将不同的请求转发至不同的处理微服务模块,其作用可视为nginx;大部分情况下用作权限鉴定、服务端流量控制

Feign 则是将当前微服务的部分服务接口暴露出来,并且主要用于各个微服务之间的服务调用

Spring Cloud Config 分布式配置中心

简介

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

使用Spring Cloud Config配置中心后的架构如下图:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第20张图片
配置中心本质上也是一个微服务,同样需要注册到Eureka服务注册中心!

Git配置管理

远程Git仓库

知名的Git远程仓库有国外的GitHub和国内的码云(gitee);但是使用GitHub时,国内的用户经常遇到的问题是访问速度太慢,有时候还会出现无法连接的情况。如果希望体验更好一些,可以使用国内的Git托管服务——码云(gitee.com)。

与GitHub相比,码云也提供免费的Git仓库。此外,还集成了代码质量检测、项目演示等功能。对于团队协作开发,码云还提供了项目管理、代码托管、文档管理的服务。本章中使用的远程Git仓库是码云。

创建远程仓库

首先要使用码云上的私有远程git仓库需要先注册帐号;请先自行访问网站并注册帐号,然后使用帐号登录码云控制台并创建公开仓库。
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第21张图片
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第22张图片

创建配置文件

在新建的仓库中创建需要被统一配置管理的配置文件。

配置文件的命名方式:{application}-{profile}.yml{application}-{profile}.properties

  • application为应用名称

  • profile用于区分开发环境,测试环境、生产环境等

user-dev.yml,表示用户微服务开发环境下使用的配置文件。

这里将user-service工程的配置文件application.yml文件的内容复制作为user-dev.yml文件的内容,具体配置如下:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第23张图片
创建 user-dev.yml ;内容来自 user-service\src\main\resources\application.yml (方便后面测试user-service项目的配置),可以如下:

server:
  port: ${port:9091}
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///springcloud
    username: root
    password: root
  application:
    # 应用名称
    name: user-service
mybatis:
  type-aliases-package: com.itheima.user.pojo
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10086/eureka #,http://localhost:10087/eureka
  instance:
    ip-address: 127.0.0.1
    # 更倾向于使用ip,而不是host名
    prefer-ip-address: true
    # 续约间隔,默认90秒
    lease-expiration-duration-in-seconds: 90
    # 服务失效时间,默认30秒
    lease-renewal-interval-in-seconds: 30

Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第24张图片
创建完user-dev.yml配置文件之后,gitee中的仓库如下:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第25张图片

搭建配置中心微服务

创建工程

创建配置中心微服务工程config-server
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第26张图片
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第27张图片
添加依赖,修改 config-server\pom.xml 如下:


<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-springcloudartifactId>
        <groupId>com.itheimagroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <groupId>com.itheimagroupId>
    <artifactId>config-serverartifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-config-serverartifactId>
        dependency>
    dependencies>

project>
启动类

创建配置中心工程 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);
    }
}
配置文件

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

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

server:
  port: 12000
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/ftbhb/heima-config.git
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka

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

启动测试

启动eureka注册中心和配置中心;然后访问http://localhost:12000/user-dev.yml ,查看能否输出在码云存储管理的user-dev.yml文件。并且可以在gitee上修改user-dev.yml然后刷新上述测试地址也能及时到最新数据。
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第28张图片

获取配置中心配置

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

如下对 user-service 工程进行改造。

添加依赖

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

<dependency>
   <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-configartifactId>
    <version>2.1.1.RELEASEversion>
dependency>
修改配置
  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
        # 配置中心服务名
        service-id: config-server

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka

user-service 工程修改后结构:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第29张图片

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

启动测试

启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service ,如果启动没有报错其实已经使用上配置中心内容,可以到注册中心查看,也可以检验 user-service 的服务。
在这里插入图片描述
接着访问:http://localhost:8080/consumer/8
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第30张图片
数据还是能查询的到!

Spring Cloud Bus 服务总线

问题

前面已经完成了将微服务中的配置文件集中存储在远程Git仓库,并且通过配置中心微服务从Git仓库拉取配置文件,当用户微服务启动时会连接配置中心获取配置信息从而启动用户微服务。

如果我们更新Git仓库中的配置文件,那用户微服务是否可以及时接收到新的配置信息并更新呢?

修改远程Git配置

修改在码云上的user-dev.yml文件,添加一个属性test.name
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第31张图片

修改UserController

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

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

package com.itheima.user.controller;

import com.itheima.user.pojo.User;
import com.itheima.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${test.name}")
    private String name;

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User queryByuId(@PathVariable Long id) {
        System.out.println("配置文件中的test.name = " + name);
        return userService.queryById(id);
    }
}
测试

依次启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service ;然后修改Git仓库中的配置信息test.name=heima2,访问用户微服务,查看输出内容。
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第32张图片
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第33张图片
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第34张图片

结论

通过查看用户微服务控制台的输出结果可以发现,我们对于Git仓库中配置文件的修改并没有及时更新到用户微服务,只有重启用户微服务才能生效。

如果想在不重启微服务的情况下更新配置该如何实现呢? 可以使用Spring Cloud Bus来实现配置的自动更新。

需要注意的是Spring Cloud Bus底层是基于RabbitMQ实现的,默认使用本地的消息队列服务,所以需要提前启动本地RabbitMQ服务(安装RabbitMQ以后才有),如下:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第35张图片

Spring Cloud Bus简介

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

使用了Spring Cloud Bus之后:
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第36张图片

改造配置中心

  1. config-server 项目的pom.xml文件中加入Spring Cloud Bus相关依赖
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-busartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-stream-binder-rabbitartifactId>
dependency>
  1. config-server 项目修改application.yml文件如下:
server:
  port: 12000
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/ftbhb/heima-config.git
  # 配置rabbitmq信息;如果是都与默认值一致则不需要配置
  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

改造用户服务

  1. 在用户微服务 user-service 项目的pom.xml中加入Spring Cloud Bus相关依赖
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-busartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-stream-binder-rabbitartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-actuatorartifactId>
dependency>
  1. 修改 user-service 项目的bootstrap.yml如下:
spring:
  cloud:
    config:
      # 要与仓库中的配置文件的application保持一致
      name: user
      # 要与仓库中的配置文件的profile保持一致
      profile: dev
      # 要与仓库中的配置文件所属的版本(分支)一样
      label: master
      discovery:
        # 使用配置中心
        enabled: true
        # 配置中心服务名
        service-id: config-server
  # 配置rabbitmq信息;如果是都与默认值一致则不需要配置
  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 Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第37张图片

测试

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

测试步骤

第一步:依次启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service

第二步:访问用户微服务http://localhost:9091/user/8;查看IDEA控制台输出结果

第三步:修改Git仓库中配置文件 user-dev.ymltest.name 内容

第四步:使用Postman或者RESTClient工具发送POST方式请求访问地址http://127.0.0.1:12000/actuator/bus-refresh
Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第38张图片
第五步:访问用户微服务系统控制台查看输出结果

说明

1、Postman或者RESTClient是一个可以模拟浏览器发送各种请求(POSTGETPUTDELETE等)的工具
 
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地址的作用是访问配置中心的消息总线服务。
 
      消息总线服务接收到请求后会向消息队列中发送消息,各个微服务会监听消息队列。
 
      当微服务接收到队列中的消息后,会重新从配置中心获取最新的配置信息。

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

Spring Cloud Gateway网关&Spring Cloud Config分布式配置中心&Spring Cloud Bus服务总线_第39张图片

代码仓库

你可能感兴趣的:(Spring,Cloud)