网关的意义:Spring Cloud Gateway实现 Spring Cloud Gateway
引用依赖:编写配置文件编写启动类:ApiGatewayApplication编写跨域类:全局Filter,统一处理会员登录与外部不允许访问的服务自定义异常
网关的意义:API 网关出现的原因是微服务架构的出现,不同的微服务一般会有不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以下的问题: (1)客户端会多次请求不同的微服务,增加了客户端的复杂性。 (由网关统一进行服务请求的分发) (2)存在跨域请求,在一定场景下处理相对复杂。 (在网关中编写跨域配置) (3)认证复杂,每个服务都需要独立认证。 (所有服务都注册在nacos服务中心中,网关通过注册中心直接获取服务信息) (4)难以重构,随着项目的迭代,可能需要重新划分微服务。例如,可能将多个服务合并成一个或者将一个服务拆分成多个。如果客户端直接与微服务通信,那么重构将会很难实施。 (不用改变客户端访问地址,直接修改网关中的配置服务信息) (5)某些微服务可能使用了防火墙 / 浏览器不友好的协议,直接访问会有一定的困难 (只需要开放网关端口,由网关统一进行服务请求的分发)Spring Cloud Gateway
Spring cloud gateway是spring官方基于Spring 5.0、Spring Boot2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供简单、有效和统一的API路由管理方式,SpringCloud Gateway作为Spring Cloud生态系统中的网关,目标是替代Netflix Zuul,其不仅提供统一的路由方式,并且还基于Filer链的方式提供了网关基本的功能,例如:安全、监控/埋点、限流等。
(1)路由。路由是网关最基础的部分,路由信息有一个ID、一个目的URL、一组断言和一组Filter组成。如果断言路由为真,则说明请求的URL和配置匹配 (2)断言。Java8中的断言函数。Spring Cloud Gateway中的断言函数输入类型是Spring5.0框架中的ServerWebExchange。Spring Cloud Gateway中的断言函数允许开发者去定义匹配来自于httprequest中的任何信息,比如请求头和参数等。 (3)过滤器。一个标准的Spring webFilter。Spring cloud gateway中的filter分为两种类型的Filter,分别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理
如上图所示,Spring cloud Gateway发出请求。然后再由Gateway Handler Mapping中找到与请求相匹配的路由,将其发送到Gateway web handler。 Handler再通过指定的过滤器链将请求发送到我们实际服务执行业务逻辑 ,然后返回。实现 Spring Cloud Gateway 引用依赖:
编写配置文件com.atguigu common_utils 0.0.1-SNAPSHOT org.springframework.cloud spring-cloud-starter-alibaba-nacos-discovery org.springframework.cloud spring-cloud-starter-gateway com.google.code.gson gson org.springframework.cloud spring-cloud-starter-openfeign
# 服务端口
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
#服务路由名小写
#spring.cloud.gateway.discovery.locator.lower-case-service-id=true
#设置路由id
spring.cloud.gateway.routes[0].id=service-acl
#设置路由的uri
spring.cloud.gateway.routes[0].uri=lb://service-acl
#设置路由断言,代理servicerId为auth-service的/auth/路径
spring.cloud.gateway.routes[0].predicates= Path=authinner
@Override
protected Map getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
Map map = new HashMap<>();
map.put("success", false);
map.put("code", 20005);
map.put("message", "网关失败");
map.put("data", null);
return map;
}
@Override
protected RouterFunction getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
@Override
protected int getHttpStatus(Map errorAttributes) {
return 200;
}
}



