谷粒学院(二十一)网关Gateway

2023-05-16

一、网关基本概念

1、API网关介绍

API 网关出现的原因是微服务架构的出现,不同的微服务一般会有不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以下的问题:

(1)客户端会多次请求不同的微服务,增加了客户端的复杂性。

(2)存在跨域请求,在一定场景下处理相对复杂。

(3)认证复杂,每个服务都需要独立认证。

(4)难以重构,随着项目的迭代,可能需要重新划分微服务。例如,可能将多个服务合并成一个或者将一个服务拆分成多个。如果客户端直接与微服务通信,那么重构将会很难实施。

(5)某些微服务可能使用了防火墙 / 浏览器不友好的协议,直接访问会有一定的困难。

以上这些问题可以借助 API 网关解决。API 网关是介于客户端和服务器端之间的中间层,所有的外部请求都会先经过 API 网关这一层。也就是说,API 的实现方面更多的考虑业务逻辑,而安全、性能、监控可以交由 API 网关来做,这样既提高业务灵活性又不缺安全性

2、Spring Cloud Gateway

Spring cloud gateway是spring官方基于Spring 5.0、Spring Boot2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供简单、有效和统一的API路由管理方式,Spring Cloud Gateway作为Spring Cloud生态系统中的网关,目标是替代Netflix Zuul,其不仅提供统一的路由方式,并且还基于Filer链的方式提供了网关基本的功能,例如:安全、监控/埋点、限流等。

在这里插入图片描述

3、Spring Cloud Gateway核心概念

网关提供API全托管服务,丰富的API管理功能,辅助企业管理大规模的API,以降低管理成本和安全风险,包括协议适配、协议转发、安全策略、防刷、流量、监控日志等贡呢。一般来说网关对外暴露的URL或者接口信息,我们统称为路由信息。如果研发过网关中间件或者使用过Zuul的人,会知道网关的核心是Filter以及Filter Chain(Filter责任链)。Sprig Cloud Gateway也具有路由和Filter的概念。下面介绍一下Spring Cloud Gateway中几个重要的概念。

(1)路由。路由是网关最基础的部分,路由信息有一个ID、一个目的URL、一组断言和一组Filter组成。如果断言路由为真,则说明请求的URL和配置匹配

(2)断言。Java8中的断言函数。Spring Cloud Gateway中的断言函数输入类型是Spring5.0框架中的ServerWebExchange。Spring Cloud Gateway中的断言函数允许开发者去定义匹配来自于http request中的任何信息,比如请求头和参数等。

(3)过滤器。一个标准的Spring webFilter。Spring cloud gateway中的filter分为两种类型的Filter,分别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理

在这里插入图片描述
如上图所示,Spring cloud Gateway发出请求。然后再由Gateway Handler Mapping中找到与请求相匹配的路由,将其发送到Gateway web handler。Handler再通过指定的过滤器链将请求发送到我们实际的服务执行业务逻辑,然后返回。

二、创建api-gateway模块(网关服务)

1、在infrastructure模块下创建api_gateway模块

在这里插入图片描述

2、在pom.xml引入依赖

<dependencies>
    <dependency>
        <groupId>com.kuang</groupId>
        <artifactId>common_utils</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

    <!--gson-->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
    </dependency>

    <!--服务调用-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
</dependencies>

3、编写application.properties配置文件

# 服务端口
server.port=8222

# 服务名
spring.application.name=service-gateway

# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

#使用服务发现路由
spring.cloud.gateway.discovery.locator.enabled=true

#配置service-acl服务
#设置路由id
spring.cloud.gateway.routes[0].id=service-acl
#设置路由的uri   lb://nacos注册服务名称
spring.cloud.gateway.routes[0].uri=lb://service-acl
#设置路由断言,代理servicerId为auth-service的/auth/路径
spring.cloud.gateway.routes[0].predicates= Path=/*/acl/**

#配置service-cms服务
spring.cloud.gateway.routes[1].id=service-cms
spring.cloud.gateway.routes[1].uri=lb://service-cms
spring.cloud.gateway.routes[1].predicates= Path=/educms/**

#配置service-edu服务
spring.cloud.gateway.routes[2].id=service-edu
spring.cloud.gateway.routes[2].uri=lb://service-edu
spring.cloud.gateway.routes[2].predicates= Path=/eduservice/**

#配置service-msm服务
spring.cloud.gateway.routes[3].id=service-msm
spring.cloud.gateway.routes[3].uri=lb://service-msm
spring.cloud.gateway.routes[3].predicates= Path=/edumsm/**

#配置service-order服务
spring.cloud.gateway.routes[4].id=service-order
spring.cloud.gateway.routes[4].uri=lb://service-order
spring.cloud.gateway.routes[4].predicates= Path=/eduorder/**

#配置service-oss服务
spring.cloud.gateway.routes[5].id=service-oss
spring.cloud.gateway.routes[5].uri=lb://service-oss
spring.cloud.gateway.routes[5].predicates= Path=/eduoss/**

#配置service-statistics服务
spring.cloud.gateway.routes[6].id=service-statistics
spring.cloud.gateway.routes[6].uri=lb://service-statistics
spring.cloud.gateway.routes[6].predicates= Path=/staservice/**

#配置service-ucenter服务
spring.cloud.gateway.routes[7].id=service-ucenter
spring.cloud.gateway.routes[7].uri=lb://service-ucenter
spring.cloud.gateway.routes[7].predicates= Path=/educenter/**

#配置service-vod服务
spring.cloud.gateway.routes[8].id=service-vod
spring.cloud.gateway.routes[8].uri=lb://service-vod
spring.cloud.gateway.routes[8].predicates= Path=/eduvod/**

4、编写启动类

@SpringBootApplication
@EnableDiscoveryClient
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
}

5、启动服务测试

http://localhost:8848/nacos
http://localhost:8001//eduservice/teacher/findAll
http://localhost:8222/eduservice/teacher/findAll

三、网关相关配置

1、网关解决跨域问题

创建配置类CorsConfig

package com.kuang.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * @Description: 统一解决跨域问题
 *  统一配置之后再每个Controller中就不用在加注解了
 * @Author: StarSea99
 * @Date: 2020-11-05 10:01
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}


2、全局Filter,统一处理会员登录与外部不允许访问的服务

package com.kuang.gateway.filter;

import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 全局Filter,统一处理会员登录与外部不允许访问的服务
 * </p>
 *
 * @Description:
 * @Author: StarSea99
 * @Date: 2020-11-05 10:01
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //谷粒学院api接口,校验用户必须登录
        if(antPathMatcher.match("/api/**/auth/**", path)) {
            List<String> tokenList = request.getHeaders().get("token");
            if(null == tokenList) {
                ServerHttpResponse response = exchange.getResponse();
                return out(response);
            } else {
//                Boolean isCheck = JwtUtils.checkToken(tokenList.get(0));
//                if(!isCheck) {
                    ServerHttpResponse response = exchange.getResponse();
                    return out(response);
//                }
            }
        }
        //内部服务接口,不允许外部访问
        if(antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            return out(response);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码,否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}

3、自定义异常处理

服务网关调用服务时可能会有一些异常或服务不可用,它返回错误信息不友好,需要我们覆盖处理

ErrorHandlerConfig:

package com.kuang.gateway.handler;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

/**
 * 覆盖默认的异常处理
 *
 * @Description:
 * @Author: StarSea99
 * @Date: 2020-11-05 10:01
 */
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfig {

    private final ServerProperties serverProperties;

    private final ApplicationContext applicationContext;

    private final ResourceProperties resourceProperties;

    private final List<ViewResolver> viewResolvers;

    private final ServerCodecConfigurer serverCodecConfigurer;

    public ErrorHandlerConfig(ServerProperties serverProperties,
                                     ResourceProperties resourceProperties,
                                     ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                        ServerCodecConfigurer serverCodecConfigurer,
                                     ApplicationContext applicationContext) {
        this.serverProperties = serverProperties;
        this.applicationContext = applicationContext;
        this.resourceProperties = resourceProperties;
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
        JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(
                errorAttributes,
                this.resourceProperties,
                this.serverProperties.getError(),
                this.applicationContext);
        exceptionHandler.setViewResolvers(this.viewResolvers);
        exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }
}

JsonExceptionHandler:

package com.kuang.gateway.handler;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义异常处理
 *
 * <p>异常时用JSON代替HTML异常信息<p>
 *
 * @Description:
 * @Author: StarSea99
 * @Date: 2020-11-05 10:01
 */
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {

    public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
                                ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    /**
     * 获取异常属性
     */
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("code", 20005);
        map.put("message", "网关失败");
        map.put("data", null);
        return map;
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    /**
     * 根据code获取对应的HttpStatus
     * @param errorAttributes
     */
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        return 200;
    }
}

4、修改前端的后端页面的端口

vue-admin-template-master项目的config/dev.env.js中
在这里插入图片描述
5、启动服务测试

这里只需要启动nacos,不用启动nginx。

问题:跨域跨了两次,导致后台访问不进去。
在这里插入图片描述
解决办法:由于我们在Gateway中配置了全局的跨域问题,所以我们需要把之前controller中写的@CrossOrigin这个注解注释掉才可以;或者把全局的CorsConfig类注掉。


如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发。
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

谷粒学院(二十一)网关Gateway 的相关文章

  • 谷粒学院(二十三)配置中心nacos

    一 配置中心介绍 1 Spring Cloud Config Spring Cloud Config 为分布式系统的外部配置提供了服务端和客户端的支持方案 在配置的服务端您可以在所有环境中为应用程序管理外部属性的中心位置 客户端和服务端概念
  • 谷粒学院-项目功能模块、技术点、整合Mybatis-Plus、主键生成策略

    Mybaitis Plus 简介 MyBatis Plus 初始化工程 使用 Spring Initializr 快速初始化一个 Spring Boot 工程 Group xff1a com nanjing Artifact xff1a m
  • 【谷粒学院】项目总结

    做谷粒学院这个项目大概花了2个多月的时间 xff0c 期间遇到了很多问题 xff0c 想要记录下来 xff0c 希望可以对别人有所帮助 首先谷粒学院项目我是不太推荐时间紧张的友友拿来做为毕设项目的 xff0c 原因是里面涉及到的技术 服务很
  • Spring Cloud Gateway(黑马springcloud笔记)

    Gateway 目录 Gateway一 为什么需要网关二 gateway入门三 断言工厂四 过滤器工厂五 全局过滤1 实现2 过滤器执行顺序 六 跨域问题 一 为什么需要网关 不能让外部能够直接访问微服务 xff0c 而是需要通过网关访问
  • 谷粒学院day09——课程发布与阿里云视频点播服务

    day9 课程信息确认与视频点播 1 课程信息确认 1 1 后端实现 1 2 前端实现 2 课程的最终发布 3 课程列表功能 4 课程删除功能 5 阿里云视频点播 5 1 获取视频地址 5 2 获取视频凭证 5 3 上传视频 6 添加小节的
  • SpringCloud Gateway API接口加解密

    接口范围 所有GET请求 白名单除外 body 体 是 application json 和 application json utf8 的 POST请求 白名单除外 POST url传参也支持 白名单除外 启用禁用 版本 后端提供独立接口
  • 分布式限流之 - Spring Cloud Gateway层限流实现

    写在前面的话 高并发的三驾马车 缓存 降级 限流 这里仅仅说限流 常用的限流算法有 计数器算法 固定窗口算法 滑动窗口算法 漏桶算法 令牌桶算法 每种算法的特点和优缺点这里不展开 比较适用的限流算法基本都会选择令牌桶 并且这里基于Sprin
  • ASP .net core 整合 nacos 通过Spring Cloud Gateway 网关访问

    ASP net core 整合 nacos 通过Spring Cloud Gateway 网关访问 使用vs创建web项目 选择api 注意这里要取消掉Https配置否则使用网关转发也需要配置为https请求这里我们直接取消 添加nacos
  • Gateway网关-网关的cors跨域配置

    什么是跨域问题 跨域 域名不一致就是跨域 主要包括 域名不同 www taobao com 和 www taobao org 和 www jd com 和 miaosha jd com 域名相同 端口不同 localhost 8080和lo
  • 微服务内部服务调用@Inner

    1 外部从Gateway访问 需要鉴权 eg CURD操作 这种是最常使 的 户登录后正常访问接 不需要我们做什么处理 可能有的接 需要加权限字段 2 外部从Gateway访问 不需要鉴权 eg 短信验证码 需要我们将uri加 到secur
  • SpringCloudGateway集成SpringDoc CORS问题

    SpringCloudGateway集成SpringDoc CORS问题 集成SpringDoc后 在gateway在线文档界面 请求具体的服务接口 报CORS问题 Failed to fetch Possible Reasons CORS
  • GateWay 服务网关

    介绍 Cloud全家桶中有个很重要的组件就是网关 在1 x版本中都是采用的Zuul网关 但在2 x版本中 zuul的升级一直跳票 SpringCloud最后自己研发了一个网关替代Zuul 那就是SpringCloud Gateway Gat
  • 微服务:gateway的使用,和解决跨域问题,用户认证与网关整合

    1 网关介绍 API网关出现的原因是微服务架构的出现 不同的微服务一般会有不同的网络地址 而外部客户端可能需要调用多个服务的接口才能完成一个业务需求 如果让客户端直接与各个微服务通信 会有以下的问题 1 客户端会多次请求不同的微服务 增加了
  • gateway整合sentinel限流不生效排查

    问题 线上的sentinel 在测试压测时候可以正常被限流 但是在正常的流量中 发现被限流的接口很少 我发誓肯定都配置了限流规则 约定 文中的 服务名称以及地址 都被改写了 排查步骤 1 检查相关配置 以及 pom依赖配置 发现Sentin
  • SpringCloud——GateWay入门

    客户由发送请求由Nginx服务器已经将请求转发到一个服务器上 但是服务之前我们还需要一个网关将这些请求进一步加工处理到服务上 这一步就是GateWay GateWay 1 GateWay服务是不需要进入以下jar包
  • Sentinel + Gateway网关动态限流

    Sentinel 控制台 0 概述 Sentinel 控制台是流量控制 熔断降级规则统一配置和管理的入口 它为用户提供了机器自发现 簇点链路自发现 监控 规则配置等功能 在 Sentinel 控制台上 我们可以配置规则并实时查看流量控制效果
  • 谷粒学院——Day09【整合阿里云视频点播】

    作者主页 Java技术一点通的博客 个人介绍 大家好 我是Java技术一点通 记得关注 点赞 收藏 评论 认真学习 共同进步 视频点播简介 一 阿里云视频点播技术能力盘点 视频点播 ApsaraVideo for VoD 是集音视频采集 编
  • 【AWS】API Gateway创建Rest API--从S3下载文件

    一 背景 在不给AK SK的前提下 用户查看s3上文件 从s3下载文件 二 创建API 1 打开API Gateway 点击创建API 选择REST API REST API和HTTP API区别 来自AWS官网 REST API 和 HT
  • .net 配置网关(使用Ocelot)

    本文演示一个最简单的demo 来模拟如何通过网关来访问服务 而不是直接访问服务 创建三个asp net core web api项目 一个作为网关 两个作为服务 分别配置项目的访问路径 网关的项目使用https localhost 5001
  • 理解gateway网关,及与前端联调过程

    1 一些概念 客户端向Spring Cloud Gateway发出请求 然后在Gateway Handler Mapping中找到请求相匹配的路由 将其发送到Gateway Web Handler Handler再通过制定的过滤器链来将请求

随机推荐