@Slf4j
public class FileUrlFilter implements GatewayFilter, Ordered {
@Override
public int getOrder() {
return 1;
}
public static RestTemplateClient restTemplateClient = (RestTemplateClient) SpringContextUtil.getBean("restTemplateClient");
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
long begin = System.currentTimeMillis();
log.info("begin time {} ms", System.currentTimeMillis() - begin);
String requestPath = exchange.getRequest().getPath().toString();
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
String fileUrl = "";
String fileName = "";
if (requestPath.indexOf("/breviary/") != -1) {
String[] breviary = requestPath.split("/breviary/");
if (breviary.length != 2) {
DataBuffer buffer = writeResponseBody(response, ResponseResultFactory.failResult("缩略图文件请求错误"));
return response.writeWith(Mono.justOrEmpty(buffer));
}
fileUrl = SecretUtil.decrypt(breviary[1], SecretUtil.URLKEY);
} else {
String[] split = requestPath.split("/fileUrl/");
//判断URL有效性
if (split.length < 2) {
DataBuffer buffer = writeResponseBody(response, ResponseResultFactory.failResult("请求错误,获取文件路径失败"));
return response.writeWith(Mono.justOrEmpty(buffer));
}
//验证有效期
if (!CheckSecretKey.checkUrlSecretKey(split[1])) {
DataBuffer buffer = writeResponseBody(response, ResponseResultFactory.failResult("您访问的地址已失效,请重新获取新的链接"));
return response.writeWith(Mono.justOrEmpty(buffer));
}
//获取真正URL
ResponseResult<Map<String, Object>> responseResult = restTemplateClient.getFileUrl(split[1]);
if (!ResponseResultFactory.CODE_SUCCESS.equals(responseResult.getCode())) {
DataBuffer buffer = writeResponseBody(response, ResponseResultFactory.failResult(responseResult.getMessage()));
return response.writeWith(Mono.justOrEmpty(buffer));
}
log.info("web time {} ms", System.currentTimeMillis() - begin);
fileUrl = responseResult.getData().get("fileUrl").toString();
fileName = responseResult.getData().get("fileName").toString();
}
String[] qqt = fileUrl.split("https://");
String host = qqt[1].split("/")[0];
String newPath = qqt[1].replace(host, "/fileUrl");
//重排请求地址
ServerHttpRequest newRequest = request.mutate()
.path(newPath)
.build();
exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, newRequest);
//修改路由地址
Route route = (Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
URI routeUri = UriComponentsBuilder.fromUri(route.getUri())
.scheme(route.getUri().getScheme())
.host(host.split(":")[0])
.port(host.split(":").length == 1 ? null : host.split(":")[1])
.build(true)
.toUri();
//应用新路由规则
Route newRoute = Route.async().asyncPredicate(route.getPredicate())
.filters(route.getFilters()).id(route.getId()).order(route.getOrder()).uri(routeUri).build();
exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR, newRoute);
log.info("beforeTrans time {} ms", System.currentTimeMillis() - begin);
//过
String finalFileName = fileName;
return chain.filter(exchange.mutate()
.request(newRequest).build()).then(Mono.fromRunnable(
() -> {
HttpHeaders headers = exchange.getResponse().getHeaders();
try {
if (StringUtils.isNotEmpty(finalFileName)) {
headers.put("Content-Disposition", Collections.singletonList("attachment; filename=" + URLEncoder.encode(finalFileName, "utf-8")));
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
log.info("获得响应中的cookie: {}", JSON.toJSONString(headers));
log.info("use time {} ms", System.currentTimeMillis() - begin);
}
)
);
}
/**
* 写入响应体信息
*
* @param response
* @param responseResult 具体信息
* @return
*/
private DataBuffer writeResponseBody(ServerHttpResponse response, Object responseResult) {
String body = JSON.toJSON(responseResult).toString();
return response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
}
}
package com.dj.filter;
import com.alibaba.fastjson.JSON;
import com.dj.common.response.ResponseResult;
import com.dj.common.response.ResponseResultFactory;
import com.dj.common.utils.CheckSecretKey;
import com.dj.common.utils.SecretUtil;
import com.dj.service.RestTemplateClient;
import com.dj.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
/**
-
文件转发校验
-
@author hq
*/
@Slf4j
public class FileUrlFilter implements GatewayFilter, Ordered {@Override
public int getOrder() {
return 1;
}public static RestTemplateClient restTemplateClient = (RestTemplateClient) SpringContextUtil.getBean(“restTemplateClient”);
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
long begin = System.currentTimeMillis();
log.info(“begin time {} ms”, System.currentTimeMillis() - begin);
String requestPath = exchange.getRequest().getPath().toString();
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
String fileUrl = “”;
String fileName = “”;
if (requestPath.indexOf(“/breviary/”) != -1) {
String[] breviary = requestPath.split(“/breviary/”);
if (breviary.length != 2) {
DataBuffer buffer = writeResponseBody(response, ResponseResultFactory.failResult(“缩略图文件请求错误”));
return response.writeWith(Mono.justOrEmpty(buffer));
}
fileUrl = SecretUtil.decrypt(breviary[1], SecretUtil.URLKEY);
} else {
String[] split = requestPath.split(“/fileUrl/”);
//判断URL有效性
if (split.length < 2) {
DataBuffer buffer = writeResponseBody(response, ResponseResultFactory.failResult(“请求错误,获取文件路径失败”));
return response.writeWith(Mono.justOrEmpty(buffer));
}
//验证有效期
if (!CheckSecretKey.checkUrlSecretKey(split[1])) {
DataBuffer buffer = writeResponseBody(response, ResponseResultFactory.failResult(“您访问的地址已失效,请重新获取新的链接”));
return response.writeWith(Mono.justOrEmpty(buffer));
}
//获取真正URL
ResponseResult<Map<String, Object>> responseResult = restTemplateClient.getFileUrl(split[1]);
if (!ResponseResultFactory.CODE_SUCCESS.equals(responseResult.getCode())) {
DataBuffer buffer = writeResponseBody(response, ResponseResultFactory.failResult(responseResult.getMessage()));
return response.writeWith(Mono.justOrEmpty(buffer));
}
log.info(“web time {} ms”, System.currentTimeMillis() - begin);
fileUrl = responseResult.getData().get(“fileUrl”).toString();
fileName = responseResult.getData().get(“fileName”).toString();
}
String[] qqt = fileUrl.split(“https://”);
String host = qqt[1].split(“/”)[0];
String newPath = qqt[1].replace(host, “/fileUrl”);
//重排请求地址
ServerHttpRequest newRequest = request.mutate()
.path(newPath)
.build();
exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, newRequest);
//修改路由地址
Route route = (Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
URI routeUri = UriComponentsBuilder.fromUri(route.getUri())
.scheme(route.getUri().getScheme())
.host(host.split(“:”)[0])
.port(host.split(“:”).length == 1 ? null : host.split(“:”)[1])
.build(true)
.toUri();
//应用新路由规则
Route newRoute = Route.async().asyncPredicate(route.getPredicate())
.filters(route.getFilters()).id(route.getId()).order(route.getOrder()).uri(routeUri).build();
exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR, newRoute);
log.info(“beforeTrans time {} ms”, System.currentTimeMillis() - begin);//过 String finalFileName = fileName; return chain.filter(exchange.mutate() .request(newRequest).build()).then(Mono.fromRunnable( () -> { HttpHeaders headers = exchange.getResponse().getHeaders(); try { if (StringUtils.isNotEmpty(finalFileName)) { headers.put("Content-Disposition", Collections.singletonList("attachment; filename=" + URLEncoder.encode(finalFileName, "utf-8"))); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } log.info("获得响应中的cookie: {}", JSON.toJSONString(headers)); log.info("use time {} ms", System.currentTimeMillis() - begin); } ) );
}
/**
- 写入响应体信息
- @param response
- @param responseResult 具体信息
- @return
*/
private DataBuffer writeResponseBody(ServerHttpResponse response, Object responseResult) {
String body = JSON.toJSON(responseResult).toString();
return response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
}
}