Spring Cloud Gateway重寫請求

在Spring Cloud中尔许,有時候需要對前端直接調(diào)用的微服務(wù)氢架,進(jìn)行請求內(nèi)容重組,這時候可以通過自定義org.springframework.cloud.gateway.filter.GlobalFilter媒吗,org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction陨舱,來滿足需求。
下面的例子共耍,是前端通過Gateway調(diào)用后端的文件服務(wù)虑灰,獲取上傳OSS的一些必要信息。通過重組痹兜,可以簡化和規(guī)范使用穆咐。

自定義RewriteFunction


import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.apache.commons.lang3.StringUtils;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import reactor.core.publisher.Mono;

@Component
public class FileServiceRequestRewriteFunction implements RewriteFunction<byte[], byte[]> {
    private static final Logger logger = LoggerFactory.getLogger(FileServiceRequestRewriteFunction.class);

    private Environment environment;
    private ObjectMapper objectMapper;
    private FileServiceProperties fileServiceProperties;

    public FileServiceRequestRewriteFunction(Environment environment, ObjectMapper objectMapper,
            FileServiceProperties fileServiceProperties) {
        this.environment = environment;
        this.objectMapper = objectMapper;
        this.fileServiceProperties = fileServiceProperties;
    }

    @Override
    public Publisher<byte[]> apply(ServerWebExchange t, byte[] u) {
        UploadTokenRequest uploadTokenRequest = new UploadTokenRequest();

        try {
            uploadTokenRequest = objectMapper.readValue(u, UploadTokenRequest.class);
        } catch (IOException e) {
            logger.error("轉(zhuǎn)換異常", e);

            return Mono.just(u);
        }

        var ossUploadFile = new OssUploadFile();

        BeanUtils.copyProperties(uploadTokenRequest, ossUploadFile);

        ossUploadFile.bucket = fileServiceProperties.getTypeBuckets().getOrDefault(uploadTokenRequest.getType(),
                fileServiceProperties.getDefaultBucket());

        ossUploadFile.prefix = getPrefix(uploadTokenRequest.getType(), uploadTokenRequest.getPrefix());

        try {
            return Mono.just(objectMapper.writeValueAsBytes(ossUploadFile));
        } catch (JsonProcessingException e) {
            logger.error("轉(zhuǎn)換異常", e);

            return Mono.just(u);
        }
    }

    private String getActiveProfile() {
        var profiles = environment.getActiveProfiles();

        return profiles.length > 0 ? profiles[0] : "";
    }

    private String getPrefix(String type, String prefix) {
        var activeProfile = getActiveProfile();
        var sb = new StringBuilder();

        if (StringUtils.isNotBlank(activeProfile) && !activeProfile.equalsIgnoreCase("prod")) {
            sb.append(activeProfile.toLowerCase());
        }

        if (StringUtils.isNotBlank(type)) {
            if (!sb.isEmpty()) {
                sb.append("/");
            }

            sb.append(type.toLowerCase());
        }

        if (StringUtils.isNotBlank(prefix)) {
            if (!sb.isEmpty()) {
                sb.append("/");
            }

            sb.append(prefix);
        } else {
            if (!sb.isEmpty()) {
                sb.append("/");
            }

            sb.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        }

        return sb.toString();
    }

    static class UploadTokenRequest {
        private String type;
        private String bucket;
        private String prefix;
        private String fileKey;
        private String sourceFile;
        private Long sourceFileSize;
        private String sourceFileType;
        private Integer useSourceFilename;
        private Long expiredInSec;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getBucket() {
            return bucket;
        }

        public void setBucket(String bucket) {
            this.bucket = bucket;
        }

        public String getPrefix() {
            return prefix;
        }

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }

        public String getFileKey() {
            return fileKey;
        }

        public void setFileKey(String fileKey) {
            this.fileKey = fileKey;
        }

        public String getSourceFile() {
            return sourceFile;
        }

        public void setSourceFile(String sourceFile) {
            this.sourceFile = sourceFile;
        }

        public Long getSourceFileSize() {
            return sourceFileSize;
        }

        public void setSourceFileSize(Long sourceFileSize) {
            this.sourceFileSize = sourceFileSize;
        }

        public String getSourceFileType() {
            return sourceFileType;
        }

        public void setSourceFileType(String sourceFileType) {
            this.sourceFileType = sourceFileType;
        }

        public Integer getUseSourceFilename() {
            return useSourceFilename;
        }

        public void setUseSourceFilename(Integer useSourceFilename) {
            this.useSourceFilename = useSourceFilename;
        }

        public Long getExpiredInSec() {
            return expiredInSec;
        }

        public void setExpiredInSec(Long expiredInSec) {
            this.expiredInSec = expiredInSec;
        }
    }

    static class OssUploadFile {
        private String bucket;
        private String prefix;
        private String fileKey;
        private String sourceFile;
        private Long sourceFileSize;
        private String sourceFileType;
        private Integer useSourceFilename;
        private Long expiredInSec;

        public String getBucket() {
            return bucket;
        }

        public void setBucket(String bucket) {
            this.bucket = bucket;
        }

        public String getPrefix() {
            return prefix;
        }

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }

        public String getFileKey() {
            return fileKey;
        }

        public void setFileKey(String fileKey) {
            this.fileKey = fileKey;
        }

        public String getSourceFile() {
            return sourceFile;
        }

        public void setSourceFile(String sourceFile) {
            this.sourceFile = sourceFile;
        }

        public Long getSourceFileSize() {
            return sourceFileSize;
        }

        public void setSourceFileSize(Long sourceFileSize) {
            this.sourceFileSize = sourceFileSize;
        }

        public String getSourceFileType() {
            return sourceFileType;
        }

        public void setSourceFileType(String sourceFileType) {
            this.sourceFileType = sourceFileType;
        }

        public Integer getUseSourceFilename() {
            return useSourceFilename;
        }

        public void setUseSourceFilename(Integer useSourceFilename) {
            this.useSourceFilename = useSourceFilename;
        }

        public Long getExpiredInSec() {
            return expiredInSec;
        }

        public void setExpiredInSec(Long expiredInSec) {
            this.expiredInSec = expiredInSec;
        }
    }
}

自定義GlobalFilter


import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * 文件服務(wù)全局過濾器
 */
@Component
public class FileServiceGatewayGlobalFilter implements GlobalFilter {
    private ModifyRequestBodyGatewayFilterFactory modifyRequestBodyGatewayFilterFactory;
    private FileServiceProperties fileServiceProperties;
    private FileServiceRequestRewriteFunction fileServiceRequestRewriteFunction;

    public FileServiceGatewayGlobalFilter(ModifyRequestBodyGatewayFilterFactory modifyRequestBodyGatewayFilterFactory,
            FileServiceProperties fileServiceProperties,
            FileServiceRequestRewriteFunction fileServiceRequestRewriteFunction) {
        this.modifyRequestBodyGatewayFilterFactory = modifyRequestBodyGatewayFilterFactory;
        this.fileServiceProperties = fileServiceProperties;
        this.fileServiceRequestRewriteFunction = fileServiceRequestRewriteFunction;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);

        if (route != null && route.getUri() != null && route.getUri().getHost().equalsIgnoreCase("file-service")) {

            var requestPath = exchange.getRequest().getURI().getPath();

            if (requestPath.equalsIgnoreCase(fileServiceProperties.getUploadTokenPath())) {
                return modifyRequestBodyGatewayFilterFactory.apply(new ModifyRequestBodyGatewayFilterFactory()
                        .newConfig().setRewriteFunction(byte[].class, byte[].class, fileServiceRequestRewriteFunction))
                        .filter(exchange, chain);

            }
        }

        return chain.filter(exchange);
    }

    static class UploadTokenRequest {
        private String type;
        private String bucket;
        private String prefix;
        private String fileKey;
        private String sourceFile;
        private Long sourceFileSize;
        private String sourceFileType;
        private Integer useSourceFilename;
        private Long expiredInSec;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getBucket() {
            return bucket;
        }

        public void setBucket(String bucket) {
            this.bucket = bucket;
        }

        public String getPrefix() {
            return prefix;
        }

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }

        public String getFileKey() {
            return fileKey;
        }

        public void setFileKey(String fileKey) {
            this.fileKey = fileKey;
        }

        public String getSourceFile() {
            return sourceFile;
        }

        public void setSourceFile(String sourceFile) {
            this.sourceFile = sourceFile;
        }

        public Long getSourceFileSize() {
            return sourceFileSize;
        }

        public void setSourceFileSize(Long sourceFileSize) {
            this.sourceFileSize = sourceFileSize;
        }

        public String getSourceFileType() {
            return sourceFileType;
        }

        public void setSourceFileType(String sourceFileType) {
            this.sourceFileType = sourceFileType;
        }

        public Integer getUseSourceFilename() {
            return useSourceFilename;
        }

        public void setUseSourceFilename(Integer useSourceFilename) {
            this.useSourceFilename = useSourceFilename;
        }

        public Long getExpiredInSec() {
            return expiredInSec;
        }

        public void setExpiredInSec(Long expiredInSec) {
            this.expiredInSec = expiredInSec;
        }
    }

    static class OssUploadFile {
        private String bucket;
        private String prefix;
        private String fileKey;
        private String sourceFile;
        private Long sourceFileSize;
        private String sourceFileType;
        private Integer useSourceFilename;
        private Long expiredInSec;

        public String getBucket() {
            return bucket;
        }

        public void setBucket(String bucket) {
            this.bucket = bucket;
        }

        public String getPrefix() {
            return prefix;
        }

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }

        public String getFileKey() {
            return fileKey;
        }

        public void setFileKey(String fileKey) {
            this.fileKey = fileKey;
        }

        public String getSourceFile() {
            return sourceFile;
        }

        public void setSourceFile(String sourceFile) {
            this.sourceFile = sourceFile;
        }

        public Long getSourceFileSize() {
            return sourceFileSize;
        }

        public void setSourceFileSize(Long sourceFileSize) {
            this.sourceFileSize = sourceFileSize;
        }

        public String getSourceFileType() {
            return sourceFileType;
        }

        public void setSourceFileType(String sourceFileType) {
            this.sourceFileType = sourceFileType;
        }

        public Integer getUseSourceFilename() {
            return useSourceFilename;
        }

        public void setUseSourceFilename(Integer useSourceFilename) {
            this.useSourceFilename = useSourceFilename;
        }

        public Long getExpiredInSec() {
            return expiredInSec;
        }

        public void setExpiredInSec(Long expiredInSec) {
            this.expiredInSec = expiredInSec;
        }
    }
}

文件服務(wù)配置


import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "file-service", ignoreUnknownFields = true)
public class FileServiceProperties {
    private String uploadTokenPath;

    private String defaultBucket;

    private Map<String, String> typeBuckets;

    public String getUploadTokenPath() {
        return uploadTokenPath;
    }

    public void setUploadTokenPath(String uploadTokenPath) {
        this.uploadTokenPath = uploadTokenPath;
    }

    public String getDefaultBucket() {
        return defaultBucket;
    }

    public void setDefaultBucket(String defaultBucket) {
        this.defaultBucket = defaultBucket;
    }

    public Map<String, String> getTypeBuckets() {
        return typeBuckets;
    }

    public void setTypeBuckets(Map<String, String> typeBuckets) {
        this.typeBuckets = typeBuckets;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市佃蚜,隨后出現(xiàn)的幾起案子庸娱,更是在濱河造成了極大的恐慌着绊,老刑警劉巖,帶你破解...
    沈念sama閱讀 207,113評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件熟尉,死亡現(xiàn)場離奇詭異归露,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)斤儿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評論 2 381
  • 文/潘曉璐 我一進(jìn)店門剧包,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人往果,你說我怎么就攤上這事疆液。” “怎么了陕贮?”我有些...
    開封第一講書人閱讀 153,340評論 0 344
  • 文/不壞的土叔 我叫張陵堕油,是天一觀的道長。 經(jīng)常有香客問我肮之,道長掉缺,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,449評論 1 279
  • 正文 為了忘掉前任戈擒,我火速辦了婚禮眶明,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘筐高。我一直安慰自己搜囱,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 64,445評論 5 374
  • 文/花漫 我一把揭開白布柑土。 她就那樣靜靜地躺著蜀肘,像睡著了一般。 火紅的嫁衣襯著肌膚如雪冰单。 梳的紋絲不亂的頭發(fā)上幌缝,一...
    開封第一講書人閱讀 49,166評論 1 284
  • 那天,我揣著相機(jī)與錄音诫欠,去河邊找鬼。 笑死浴栽,一個胖子當(dāng)著我的面吹牛荒叼,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播典鸡,決...
    沈念sama閱讀 38,442評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼被廓,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了萝玷?” 一聲冷哼從身側(cè)響起嫁乘,我...
    開封第一講書人閱讀 37,105評論 0 261
  • 序言:老撾萬榮一對情侶失蹤昆婿,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后蜓斧,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體仓蛆,經(jīng)...
    沈念sama閱讀 43,601評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,066評論 2 325
  • 正文 我和宋清朗相戀三年挎春,在試婚紗的時候發(fā)現(xiàn)自己被綠了看疙。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,161評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡直奋,死狀恐怖能庆,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情脚线,我是刑警寧澤搁胆,帶...
    沈念sama閱讀 33,792評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站邮绿,受9級特大地震影響丰涉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜斯碌,卻給世界環(huán)境...
    茶點故事閱讀 39,351評論 3 307
  • 文/蒙蒙 一一死、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧傻唾,春花似錦投慈、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至凛辣,卻和暖如春抱既,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背扁誓。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評論 1 261
  • 我被黑心中介騙來泰國打工防泵, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蝗敢。 一個月前我還...
    沈念sama閱讀 45,618評論 2 355
  • 正文 我出身青樓捷泞,卻偏偏與公主長得像,于是被迫代替她去往敵國和親寿谴。 傳聞我的和親對象是個殘疾皇子锁右,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,916評論 2 344

推薦閱讀更多精彩內(nèi)容