gateway静态路由变更访问地址并且修改响应请求头

@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));
      }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

張弎疯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值