Gateway服务网关

为什么需要网关
网关功能:1让不让你过去, 2你去哪 3限流保护

网关的技术实现
用SpringCloudGateway来实现

搭建网关服务
-
创建gateway模块,引入SpringCloudGateway依赖和nacos服务注册发现依赖
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies> -
编写nacos地址及路由配置
ymlserver: port: 10010 # 网关端口 spring: application: name: gateway # 服务名称 cloud: nacos: server-addr: localhost:8848 # nacos地址 gateway: routes: # 网关路由配置 - id: user-service # 路由id,自定义,只要唯一即可 # uri: http://127.0.0.1:8081 # 路由的目标地址 http就是固定地址 uri: lb://userservice # 路由的目标地址。 lb就是负载均衡,后面跟服务名称 predicates: # 路由断言,判断请求是否符合规则 - Path=/user/** # 判断路径是否以/user/开头,是就符合要求 - id: order-service uri: lb://orderservice predicates: - Path=/order/**
启动程序
java@EnableFeignClients(clients = {UserClient.class},defaultConfiguration = DefaultFeignConfiguration.class) //@MapperScan("com.itheima.gateway.mapper") @SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }

小结

路由断言工厂 Route Predicate Factory

作用:读取并解析用户定义的断言

Spring提供了11种基本的Predicate工厂:
名称 | 说明 | 示例 |
---|---|---|
After | 是某个时间点后的请求 | - After=2037-01-20T17:42:47.789-07:00[America/Denver] |
Before | 是某个时间点之前的请求 | - Before=2031-04-13T15:14:47.433+08:00[Asia/Shanghai] |
Between | 是某两个时间点之前的请求 | - Between=2037-01-20T17:42:47.789-07:00[America/Denver], 2037-01-21T17:42:47.789-07:00[America/Denver] |
Cookie | 请求必须包含某些cookie | - Cookie=chocolate, ch.p |
Header | 请求必须包含某些header | - Header=X-Request-Id, \d+ |
Host | 请求必须是访问某个host(域名) | - Host=.somehost.org,.anotherhost.org |
Method | 请求方式必须是指定方式 | - Method=GET,POST |
Path | 请求路径必须符合指定规则 | - Path=/red/{segment},/blue/** |
Query | 请求参数必须包含指定参数 | - Query=name, Jack或者- Query=name |
RemoteAddr | 请求者的ip必须是指定范围 | - RemoteAddr=192.168.1.1/24 |
Weight | 权重处理 |
小结

路由过滤器 GatewayFilter
GatewayFilter是网关中提供的一种过滤器,可以对进入网关的请求 和微服务返回的响应做处理:

Spring提供了31种不同的路由过滤器工厂 GatewayFilterFactory。例如:
名称 | 说明 |
---|---|
AddRequestHeader | 给当前请求添加一个请求头 |
RemoveRequestHeader | 移除请求中的一个请求头 |
AddResponseHeader | 给响应结果中添加一个响应头 |
RemoveResponseHeader | 从响应结果中移除有一个响应头 |
RequestRateLimiter | 限制请求的流量 |
... |
案例

在gataway服务的配置文件中

在user-service中

重启两个服务,并在浏览器访问http://localhost:10010/user/1

在user-service控制台

如果要对所有的路由都生效,则可以将过滤器工厂写到default下。格式如下:


小结

全局过滤器 GlobalFilter
全局过滤器的作用也是处理一切进入网关的请求和微服务响应,与GatewayFilter的作用一样。
区别在于:GatewayFilter通过配置定义,处理逻辑是固定的,可以完成简单的业务逻辑。而复杂的业务逻辑需要用GlobalFilter自己写代码实现。
定义全局过滤器方式是实现GlobalFilter接口。

案例

全局过滤器定义在gateway服务中,代码如下
java
package com.itheima.gateway;
import jdk.nashorn.internal.ir.CallNode;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
//@Order(-1)//顺序组件,值越小越高
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//1 获取请求参数
ServerHttpRequest request = exchange.getRequest();
//2 获取参数中的 authorization 参数
MultiValueMap<String, String> queryParams = request.getQueryParams();
String auth = queryParams.getFirst("authorization");//取出第一个匹配的
//3 判断参数是否为等于 admin
if ("admin".equals(auth)){
//4 放行
return chain.filter(exchange);
}
//5 拦截
//5.1 设置状态码
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//5.2 拦截请求
return exchange.getResponse().setComplete();
}
@Override
public int getOrder() {
return -1;
}
}
重启服务,访问浏览器结果如下

小结

过滤器的执行顺序

问题:怎么排序呢?
- order值越小,优先级越高
- order值一样时,按defaultFilter > 路由过滤器 > GlobalFilter 执行

网关跨域问题处理
跨域:域名不一致,主要包括:
-
域名不同: www.taobao.com 和 www.taobao.org 和 www.jd.com 和 miaosha.jd.com
-
域名相同,端口不同:localhost:8080和localhost8081
跨域问题:浏览器禁止请求的发起者与服务端发生跨域ajax请求,请求被浏览器拦截的问题
解决方案:CORS
网关处理跨域采用的同样是CORS方案,并且只需要简单配置即可实现:
yaml
spring:
cloud:
gateway:
# 。。。
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题 (这样设置 网关不拦截CORS的询问请求)
corsConfigurations:
'[/**]': #/** 表示进入网关一切请求 都做跨域处理
allowedOrigins: # 允许哪些网站的跨域请求 (允许哪些域名跨域)
- "http://localhost:8090"
- "http://www.leyou.com"
allowedMethods: # 允许的跨域ajax的请求方式 (允许哪些请求方式跨域)
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息 (允许请求头跨域,*代表一切请求头)
allowCredentials: true # 是否允许携带cookie (跨域时 允许带cookie)
maxAge: 360000 # 这次跨域检测的有效期
