gateWay网关负载均衡报404错误,我的yml文件配置
spring:
cloud:
gateway:
locator:
enabled: true
loadbalancer:
# 服务找不到404
use404: true
routes:
# 认证中心
- id: lxyyf-auth
uri: lb://lxyyf-auth
predicates:
- Path=/auth/**
filters:
# 验证码处理
- ValidateCodeGatewayFilter
# 前端密码解密
- PasswordDecoderFilter
#UPMS 模块
- id: lxyyf-upms-biz
uri: lb://lxyyf-upms-biz
predicates:
- Path=/admin/**
filters:
# 限流配置
- name: RequestRateLimiter
args:
key-resolver: '#{@remoteAddrKeyResolver}'
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
# 降级配置
- name: Hystrix
args:
name: default
fallbackUri: 'forward:/fallback'
# 代码生成模块
- id: lxyyf-codegen
uri: lb://lxyyf-codegen
predicates:
- Path=/gen/**
# 用户中心
- id: lxyyf-ucenter
uri: lb://lxyyf-ucenter
predicates:
- Path=/ucenter/**
filters:
- StripPrefix=1 #去掉Path前缀,参数为1代表去掉/ucenter
security:
validate:
code: false
oauth2:
client:
client-id: pig
client-secret: pig
scope: server
encode:
# 前端密码密钥,必须16位
key: 'thanks,pig4cloud'
# 不校验验证码终端
ignore:
clients:
- test
urls:
- /api/code/**
- /auth/**
- /ucenter/**
lxyyf-ucenter 负载到这个服务时,404错误,通过debug源码(注意logback的日志级别调为debug级别,请求的实际地址打印不出来)。日志打印的请求信息,url被截取了两次,StripPrefix=1 自带的过滤器会根据/截取一次,我自定义的RequestGlobalFilter过滤器又截取了一次,
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. 清洗请求头中from 参数
ServerHttpRequest request = exchange.getRequest().mutate()
.headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM))
.build();
// 2. 重写StripPrefix,默认截取一次,截取第一段,配置文件中无需再配置 StripPrefix=1 不然会截取两次
addOriginalRequestUrl(exchange, request.getURI());
String rawPath = request.getURI().getRawPath();
log.info("rawPath:{}",rawPath);
String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
.skip(1L).collect(Collectors.joining("/"));
log.info("newPath:{}",newPath);
ServerHttpRequest newRequest = request.mutate()
.path(newPath)
.build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
return chain.filter(exchange.mutate()
.request(newRequest.mutate()
.build()).build());
}
请求的源路径:http://localhost:9999/ucenter/useCenter/hello到底层变为http://localhost:4009/hello了,所以报404错误
整合Security,忽略一些url
参考:https://blog.csdn.net/MongolianWolf/article/details/94329980
来源:oschina
链接:https://my.oschina.net/u/3971821/blog/4264914