一步一步学SpringCloud--getway配置详解
SpringCloud Gateway配置详解
- 前言
- 一、引入pom依赖
- 二、配置文件
- 1、路由配置
- 2、跨域配置
- 三、重要的filter
- 1、StripPrefix
- 2、Hystrix熔断
- 3、自定义gateway filter
- 4、自定义限流gateway filter
前言
在上一篇文章中简单的介绍了SpringCloud Gateway,同时也对比了一下springcloud的gateway和Netflix的zuul,相信大家也有了一定的认识。此篇文章主要介绍一下gateway是如何配置的。同其他
一、引入pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
二、配置文件
1、路由配置
spring:
application:
name: gateway
profiles:
active: dev
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
routes:
- id: foo # foo服务
uri: lb://integral-foo
predicates:
- Path=/foo-web/**
filters:
- StripPrefix=1
server:
port: 1001
eureka:
instance:
instance-id: ${ spring.application.name}:${ random.int}
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:8761/eureka
routes:具体的路由信息,是一个数组
- id:这个路由的唯一id,不定义的话默认为一个uuid
- uri:http请求为lb://前缀+服务id;ws请求为lb
//前缀+服务id,表示将请求负载到哪个服务上
- predicates:表示这个路由的请求匹配规则,只有符合这个规则的请求才会走这个路由。每个规则为并且的关系。
- filters:请求转发前的filter
- order:这个路由的执行order
2、跨域配置
spring:
application:
name: gateway
profiles:
active: dev
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
maxAge: 1800
allowedOrigins: "*"
allowCredentials: true
allowedMethods:
- GET
- POST
- PUT
- DELETE
- allowedOrigins:允许的请求
- allowCredentials:允许凭证
- allowedMethods:允许的方法请求方式
关于跨域的配置SpringCloud Gateway官网上写的已经很详细了。但是有一点没有提到,前后端交互的时候OPTIONS请求没有跨过去,yml文件里面只能配置get,post,put,delete等等这些请求,配置了OPTIONS不起作用。那么就需要我们再添加一个配置类来专门处理OPTIONS请求。
/** * @author 刘子腾 * @DESCRIPTION 网关跨域 * @create 2019/3/12 */
@Configuration
public class CorsConfig {
private static final String ALL = "*";
private static final String MAX_AGE = "18000";
@Bean
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
if (!CorsUtils.isCorsRequest(request)) {
return chain.filter(ctx);
}
HttpHeaders requestHeaders = request.getHeaders();
ServerHttpResponse response = ctx.getResponse();
HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
HttpHeaders headers = response.getHeaders();
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
if (requestMethod != null) {
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
}
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode( HttpStatus.OK);
return Mono.empty();
}
return chain.filter(ctx);
};
}
}
三、重要的filter
1、StripPrefix
spring:
cloud:
gateway:
routes:
- id: nameRoot
uri: lb://nameservice
predicates:
- Path=/name/**
filters:
- StripPrefix=1
/name/bar/foo的请求会被转发为http://nameserviceip:nameserviceport/bar/foo
2、Hystrix熔断
1)引入pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2)配置文件
spring:
cloud:
gateway:
default-filters:
routes:
#------------------------------------------------------------------------
- id: i5xforyou-biz-auth
uri: lb://i5xforyou-biz-auth
predicates:
- Path= ${ server.servlet.context-path}/auth/**
filters:
- StripPrefix= 1
- name: Hystrix
args:
name: authHystrixCommand
fallbackUri: forward:/hystrixTimeout
#设置断路由的超时时间,毫秒
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds= 30000
name表示HystrixCommand代码的名称,fallbackUri表示触发断路由后的跳转请求url
3、自定义gateway filter
自定义一个用来检验jwt是否合法的gateway filter为例进行说明。
1)定义一个JwtCheckGatewayFilterFactory类实现GatewayFilterFactory接口。
类名一定要为filterName + GatewayFilterFactory,如这里定义为JwtCheckGatewayFilterFactory的话,它的filterName就是JwtCheck
2)实现gateway filter的业务逻辑
@Component
public class JwtCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
//return chain.filter(exchange);
String jwtToken = exchange.getRequest().getHeaders().getFirst("Authorization");
//校验jwtToken的合法性
if (JwtUtil.verifyToken(jwtToken) != null) {
//合法
return chain.filter(exchange);
}
//不合法
ServerHttpResponse response = exchange.getResponse();
//设置headers
HttpHeaders httpHeaders = response.getHeaders();
httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
//设置body
JsonPackage jsonPackage = new JsonPackage();
jsonPackage.setStatus(110);
jsonPackage.setMessage("未登录或登录超时");
DataBuffer bodyDataBuffer = response.bufferFactory().wrap(jsonPackage.toJSONString().getBytes());
return response.writeWith(Mono.just(bodyDataBuffer));
};
}
}
3)配置文件
spring:
cloud:
gateway:
default-filters:
routes:
#------------------------------------------------------------------------
- id: i5xforyou-biz-auth
uri: lb://i5xforyou-biz-auth
predicates:
- Path= ${ server.servlet.context-path}/auth/**
filters:
- StripPrefix= 1
- JwtCheck
4、自定义限流gateway filter
gateway自带的RequestRateLimiter可定制的内容太少,真正用的话,需要:
- 自定义限流后的response返回值
- 不同的key(即接口)限流数不同
还没有评论,来说两句吧...