Spring Cloud Gateway 攔截響應(yīng)問(wèn)題分析(數(shù)據(jù)截?cái)鄦?wèn)題)
Spring Cloud Gateway是Spring 官方基于Spring 5.0、Spring Boot 2.0和Project Reactor等技術(shù)開(kāi)發(fā)的網(wǎng)關(guān),Spring Cloud Gateway旨在為微服務(wù)架構(gòu)提供一種簡(jiǎn)單有效的、統(tǒng)一的 API 路由管理方式。
Spring Cloud Gateway 作為 Spring Cloud 生態(tài)系中的網(wǎng)關(guān),其目標(biāo)是替代 Netflix Zuul,它不僅提供統(tǒng)一的路由方式,并且基于Filter鏈的方式提供了網(wǎng)關(guān)基本的功能,如:安全、監(jiān)控/埋點(diǎn)和限流等。
Spring Cloud Gateway依賴(lài)Spring Boot和Spring WebFlux,基于Netty 運(yùn)行。不能在傳統(tǒng)的 servlet 容器中工作也不能構(gòu)建成war包。
關(guān)于Spring Cloud Gateway 核心概念
1、Route
Route 是網(wǎng)關(guān)的基礎(chǔ)元素,由 ID、目標(biāo) URI、斷言、過(guò)濾器組成。當(dāng)請(qǐng)求到達(dá)網(wǎng)關(guān)時(shí),由 Gateway HandlerMapping 通過(guò)斷言進(jìn)行路由匹配(Mapping),斷言為真時(shí)匹配到路由。
2、Predicate
Predicate 是 Java 8 中提供的一個(gè)函數(shù)。輸入類(lèi)型是 Spring Framework ServerWebExchange。它允許開(kāi)發(fā)人員匹配來(lái)自 HTTP 的請(qǐng)求,例如請(qǐng)求頭或者請(qǐng)求參數(shù)。簡(jiǎn)單來(lái)說(shuō)它就是匹配條件。
3、Filter
Filter是Gateway 中的過(guò)濾器,可以在請(qǐng)求發(fā)出前后進(jìn)行一些業(yè)務(wù)上的處理。
Spring Cloud Gateway 攔截響應(yīng)
最近因?yàn)樯湘溌纷粉櫤蟀l(fā)現(xiàn)如果在服務(wù)層將異常攔截掉,在鏈路追蹤界面上就不會(huì)顯示異常鏈路信息,除了服務(wù)異常意外,系統(tǒng)的異常不會(huì)觸發(fā)鏈路error,所以對(duì)服務(wù)層做了個(gè)變更,將所有未處理異常直接捕獲后統(tǒng)一封裝完拋出,這個(gè)時(shí)候就需要在網(wǎng)關(guān)層統(tǒng)一處理那么網(wǎng)關(guān)需要對(duì)響應(yīng)數(shù)據(jù)進(jìn)行攔截如果是 9999錯(cuò)誤碼,則封裝后返回,如果是其它響應(yīng)碼或者其它數(shù)據(jù)直接返回。
起初寫(xiě)法測(cè)試后發(fā)現(xiàn)數(shù)據(jù)過(guò)長(zhǎng)時(shí)被截?cái)唷?/p>
return super.writeWith(fluxBody.map(dataBuffer -> {
byte[] content = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(content);
// 釋放掉內(nèi)存
DataBufferUtils.release(dataBuffer);
String str = new String(content, Charset.forName("UTF-8"));
originalResponse.getHeaders().setContentLength(str.getBytes().length);
log.error("gateway catch service exception error:"+ str);
JsonResult result = new JsonResult();
result.setCode(ErrorCode.SYS_EXCEPTION.getCode());
result.setMessage(ErrorCode.SYS_EXCEPTION.getMsg());
return bufferFactory.wrap(str.getBytes());
})); 查詢(xún)api后發(fā)現(xiàn)存在一個(gè)DataBufferFactory可以一次性join完所有數(shù)據(jù)后拼接就不會(huì)產(chǎn)生截?cái)鄦?wèn)題。
DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
于是修改代碼如下
package com.server.gateway.filters;
import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.http.protocol.HTTP;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import com.framework.common.enums.ErrorCode;
import com.framework.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class WrapperResponseGlobalFilter implements GlobalFilter, Ordered{
@Override
public int getOrder() {
// -1 is response write filter, must be called before that
return -2;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponse originalResponse = exchange.getResponse();
DataBufferFactory bufferFactory = originalResponse.bufferFactory();
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
AtomicReference<String> bodyRef = new AtomicReference<>();
if (body instanceof Flux) {
Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
DataBuffer join = dataBufferFactory.join(dataBuffers);
byte[] content = new byte[join.readableByteCount()];
join.read(content);
// 釋放掉內(nèi)存
DataBufferUtils.release(join);
String str = new String(content, Charset.forName("UTF-8"));
originalResponse.getHeaders().setContentLength(str.getBytes().length);
log.error("gateway catch service exception error:"+ str);
JsonResult result = new JsonResult();
result.setCode(ErrorCode.SYS_EXCEPTION.getCode());
result.setMessage(ErrorCode.SYS_EXCEPTION.getMsg());
return bufferFactory.wrap(str.getBytes());
}));
}
// if body is not a flux. never got there.
return super.writeWith(body);
}
};
// replace response with decorator
return chain.filter(exchange.mutate().response(decoratedResponse).build());
}
}經(jīng)過(guò)如上修改后鏈路追蹤可以實(shí)現(xiàn)哪個(gè)服務(wù)出錯(cuò)就立馬出現(xiàn)鏈路異常馬上可以定位到哪個(gè)服務(wù)出現(xiàn)了未處理異常

到此這篇關(guān)于Spring Cloud Gateway 攔截響應(yīng)(數(shù)據(jù)截?cái)鄦?wèn)題)的文章就介紹到這了,更多相關(guān)Spring Cloud Gateway 攔截響應(yīng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot項(xiàng)目中application.properties無(wú)法變成小樹(shù)葉問(wèn)題解決方案
這篇文章主要介紹了springboot項(xiàng)目中application.properties無(wú)法變成小樹(shù)葉問(wèn)題解決,本文通過(guò)圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09
SpringBoot應(yīng)用能直接運(yùn)行java -jar的原因分析
這篇文章主要介紹了SpringBoot應(yīng)用為什么能直接運(yùn)行java -jar,首先明確一點(diǎn),普通jar包是不能直接運(yùn)行的,比如工具類(lèi)jar,要能運(yùn)行,至少得要一個(gè)main函數(shù)作為入口吧?本文給大家介紹了詳細(xì)的原因分析,需要的朋友可以參考下2024-03-03
java?Export大量數(shù)據(jù)導(dǎo)出和打包
這篇文章主要為大家介紹了java?Export大量數(shù)據(jù)的導(dǎo)出和打包實(shí)現(xiàn)過(guò)程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Java for循環(huán)Map集合優(yōu)化實(shí)現(xiàn)解析
這篇文章主要介紹了Java for循環(huán)Map集合優(yōu)化實(shí)現(xiàn)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
SpringBoot+MyBatis簡(jiǎn)單數(shù)據(jù)訪問(wèn)應(yīng)用的實(shí)例代碼
這篇文章主要介紹了SpringBoot+MyBatis簡(jiǎn)單數(shù)據(jù)訪問(wèn)應(yīng)用的實(shí)例代碼,需要的朋友可以參考下2017-05-05
spring 定時(shí)任務(wù)@Scheduled詳解
這篇文章主要介紹了spring 定時(shí)任務(wù)@Scheduled的相關(guān)資料,文中通過(guò)示例代碼介紹的很詳細(xì),相信對(duì)大家的理解和學(xué)習(xí)具有一定的參考借鑒價(jià)值,有需要的朋友們下面來(lái)一起看看吧。2017-01-01
maven-surefire-plugin總結(jié)示例詳解
這篇文章主要介紹了maven-surefire-plugin總結(jié),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
webuploader+springmvc實(shí)現(xiàn)圖片上傳功能
這篇文章主要為大家詳細(xì)介紹了webuploader+springmvc實(shí)現(xiàn)圖片上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09

