依赖
springGate需要向nacos注册服务才能找到别的服务
所以需要nacos客户端依赖
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Nacos Discovery注册发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
yaml文件
server:
port: 10010
spring:
application:
name: gateway
cloud:
nacos:
server-addr: localhost:8848 #nacos地址
gateway:
routes:
- id: user-service # 路由标识, 必须唯一
uri: lb://userservice # 路由的目标地址 lb是负载均衡的意思
predicates: #路由断言, 判断请求是否符合规则
- Path=/user/** #配置路径断言, 判断路径是否是以/user开头, 如果是则符合
# filters:
# - AddRequestHeader=Truth, Itcast is freaking aosome!
- id: order-service #路由标识
uri: lb://orderservice #路由的目标地址
predicates:
- Path=/order/** #路径断言
default-filters:
- AddRequestHeader=Truth, Itcast is freaking aosome!
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOrigins: # 允许哪些网站的跨域请求
- "http://localhost:8090"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
启动类
package cn.itcast.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
GlobalFilter
@Order(-1 )
@Component
public class AuthorizeFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//获取请求参数
ServerHttpRequest request = exchange.getRequest();
MultiValueMap<String, String> params = request.getQueryParams();
//获取参数中的authorizeFilter
String auth = params.getFirst("authorizeFilter");
//判断参数值是否等于admin
if ("admin".equals(auth)) {
//4.是 放行
return chain.filter(exchange);
}
//5.1设置响应状态码
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//5.拦截
return exchange.getResponse().setComplete();
}
}
过滤器链执行顺序
GlobalFilter可以通过 @Order(-1 ) 自己设置order等级
数值越小, 优先级越高
cors跨域配置
跨域是针对前端的(不然之前用 Feign 调用别的微服务就需要配置跨域了)
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOrigins: # 允许哪些网站的跨域请求
- "http://localhost:8090"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
(在gateway下面)