首页 > 其他分享 >微服务Spring Cloud17_Spring Cloud Gateway网关10

微服务Spring Cloud17_Spring Cloud Gateway网关10

时间:2024-05-13 13:08:25浏览次数:14  
标签:10 网关 http Spring Gateway user 过滤器 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加入后的架构

 

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

 三、核心概念

  • 路由(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将会对请求和响应进行修改处理。 

四、快速入门

 1、新建工程

  填写基本信息:

  

  

  打开 heima-springcloud\heima-gateway\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>com.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.itheima</groupId>
    <artifactId>heima-gateway</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>
</project>

 2、编写启动类

  在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);
   }
}

 3、编写配置

  创建 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

 4、编写路由规则 需要用网关来代理 user-service 服务,先看一下控制面板中的服务状态:   

  

  • 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 

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

  

 五、面向服务的路由

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

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

 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中获取具体服务
         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、启动测试

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

  日志中可以看到使用了负载均衡器: 

  

 六、路由前缀

 1、添加前缀

  在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
          # 代理的服务地址;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 来指定了路由要添加的前缀。

  也就是:

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

  以此类推。

   

 2、去除前缀

  在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
          # 代理的服务地址;lb表示从eureka中获取具体服务
         uri: lb://user-service
          # 路由断言,可以配置映射路径
         predicates:
           - Path=/api/user/**
         filters:
            # 表示过滤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

  以此类推。

  

 七、过滤器

 1、简介

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

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

   

   

  详细的说明在官网链接  

  • 配置全局默认过滤器

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

   了解如下: 

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 的话;那么可以从其响应中查看到如下信息: 

   

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

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

    2. 全局过滤器:不需要在配置文件中配置,作用在所有的路由上;实现 GlobalFilter 接口即可。

 2、执行生命周期

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

  

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

 3、使用场景

  常见的应用场景如下:

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

八、自定义过滤器

 1、自定义局部过滤器

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

  1)编写过滤器

   在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> {
    public static final String PARAM_NAME = "param";
    public MyParamGatewayFilterFactory() {
        super(Config.class);
   }
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM_NAME);
   }
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
           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;
       }
   }
}

  2)修改配置文件

   在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
          # 代理的服务地址;lb表示从eureka中获取具体服务
         uri: lb://user-service
          # 路由断言,可以配置映射路径
         predicates:
           - Path=/api/user/**
         filters:
            # 表示过滤1个路径,2表示两个路径,以此类推
           - StripPrefix=1
            # 自定义过滤器
           - MyParam=name
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 则是不会输出的。

 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;
@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

   

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

   

 九、负载均衡和熔断(了解)

 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/mul ti__cors_configuration.html 

十一、Gateway的高可用(了解)

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

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

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

十二、Gateway与Feign的区别

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

 

标签:10,网关,http,Spring,Gateway,user,过滤器,gateway,路由
From: https://www.cnblogs.com/ajing2018/p/18189006

相关文章

  • 洛谷题单指南-动态规划3-P3205 [HNOI2010] 合唱队
    原题链接:https://www.luogu.com.cn/problem/P3205题意解读:给定理想队形,计算初始队形的方案数。解题思路:对于给定理想队形,最后一个人插入有两种可能:从左边插入、从右边插入从左边插入,则意味着前一个数比当前数大,前一个数有可能在左边也有可能在右边从右边插入,则意味着前一个数......
  • win10 22H2
    Windows10updatehistoryhttps://support.microsoft.com/en-gb/topic/windows-10-update-history-8127c2c6-6edf-4fdf-8b9f-0f7be1ef3562UpdatesforWindows10,version22H2April9,2024—KB5036892(OSBuilds19044.4291and19045.4291) ......
  • 谈谈 Spring 的过滤器和拦截器
    前言我们在进行Web应用开发时,时常需要对请求进行拦截或处理,故Spring为我们提供了过滤器和拦截器来应对这种情况。那么两者之间有什么不同呢?本文将详细讲解两者的区别和对应的使用场景。(本文的代码实现首先是基于SpringBoot,Spring的实现方式仅简单描述)1.过滤器1.1.......
  • 从XML配置角度理解Spring AOP
    本文分享自华为云社区《Spring高手之路18——从XML配置角度理解SpringAOP》,作者:砖业洋__。1.SpringAOP与动态代理1.1SpringAOP和动态代理的关系SpringAOP使用动态代理作为其主要机制来实现面向切面的编程。这种机制允许Spring在运行时动态地创建代理对象,这些代理对象包......
  • P10217 [省选联考 2024] 季风
    [原题链接](https://www.luogu.com.cn/problem/P10217) 发现一定是若干个整段数组和一个前缀,可以枚举长度模$n$的余数,即位前缀。记当前位置为$i$,当前$x$数组前缀和为$sum1$,$y$数组为$sum2$,$x$数组总和为$sumx$,$y$数组总和为$sumy$。整段数组的个数为$m$,答案即......
  • STM32Cube-10 | 使用ADC读取气体传感器数据(MQ-2)
    本篇详细的记录了如何使用STM32CubeMX配置STM32L431RCT6的ADC外设,读取MQ-2气体传感器的数据并通过串口发送本质就是ADC采集MQ-2的原理图如下: 生成MDK工程选择芯片型号打开STM32CubeMX,打开MCU选择器:搜索并选中芯片STM32L431RCT6:配置时钟源如果选择使用外......
  • springmvc+swagger2+struts2
    jar包<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.7</version> </dependency> <dependency> <groupId>com.fasterxml.ja......
  • windows10ltsc 企业评估版,系统到期后,每一小时自动关机,不能修改主题
    问题1:参照https://www.zhihu.com/question/265212829答案太详细了,难以补充什么大概是用PSTool进入Systemaccount来获得修改WLMS的注册表的权限,把在注册表里把HKLM\SYSTEM\CurrentControlSet\Services\WLMS选择WLMS,在右侧选项“Start”中,将数值2改成4问题2:参照https://w......
  • springboot内嵌tomcat的实现原理
    目录一、tomcat运行原理的简单分析1.1Coyote1.2容器catalina二、用编码的方式启动tomcat一、tomcat运行原理的简单分析tomcat运行时可以简单分成两个大的模块,(1)负责处理socket连接并转换成request对象的部分,连接器Coyote(2)处理用户的请求的容器Catalina下面简单介绍......
  • Spring6 的JdbcTemplate的JDBC模板类的详细使用说明
    1.Spring6的JdbcTemplate的JDBC模板类的详细使用说明@目录1.Spring6的JdbcTemplate的JDBC模板类的详细使用说明每博一文案2.环境准备3.数据准备4.开始4.1从数据表中插入(添加)数据4.2从数据表中修改数据4.3从数据表中删除数据4.4从数据表中查询一个对象4.5从数据表中......