像这样:
spring:
cloud:
gateway:
routes:
- id: static-file
uri: file:///data/pub/
predicates:
- Path=/file/**
它支持吗?
我想以ResourceHandlerRegistry.addResourceHandler
这种方式替换。
问问题
43 次
1 回答
0
我的实现是这样的:
@Component
public class GlobalFileRoutingFilter implements GlobalFilter, Ordered {
private static final Log log = LogFactory.getLog(GlobalFileRoutingFilter.class);
private final DispatcherHandler dispatcherHandler;
public GlobalFileRoutingFilter(DispatcherHandler dispatcherHandler) {
this.dispatcherHandler = dispatcherHandler;
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
Route route = (Route)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
if (route == null) {
return chain.filter(exchange);
} else {
log.trace("GlobalFileRoutingFilter start");
URI routeUri = route.getUri();
String scheme = routeUri.getScheme();
if (isAlreadyRouted(exchange) || !"file".equals(scheme)) {
return chain.filter(exchange);
}
setAlreadyRouted(exchange);
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
String filePath = routeUri.getPath() + File.separator + request.getURI().getPath();
if (log.isTraceEnabled()) {
log.trace("Reading from file: "+filePath);
}
if ("HEAD".equalsIgnoreCase(request.getMethod().toString())) {
response.getHeaders().set(HttpHeaders.ACCEPT_RANGES, "none");
} else {
File file = new File(filePath);
if (!file.exists()) {
response.setStatusCode(HttpStatus.NOT_FOUND);
} else {
DataBuffer dataBuffer = response.bufferFactory().allocateBuffer();
try {
dataBuffer.write(IOUtils.toByteArray(new FileInputStream(file)));
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error(e);
}
}
return response.writeAndFlushWith(Flux.just(Flux.just(dataBuffer)));
}
}
return Mono.empty();
}
}
}
于 2018-07-04T05:56:52.910 回答