您好,登錄后才能下訂單哦!
這篇文章主要講解了“Spring Cloud Gateway怎么修改HTTP響應(yīng)信息”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“Spring Cloud Gateway怎么修改HTTP響應(yīng)信息”吧!
實(shí)踐Spring Cloud的過(guò)程中,使用Gateway作為路由組件,并且基于Gateway實(shí)現(xiàn)權(quán)限的驗(yàn)證、攔截、過(guò)濾,對(duì)于下游微服務(wù)的響應(yīng)結(jié)果,我們總會(huì)有需要修改以統(tǒng)一數(shù)據(jù)格式,或者修改過(guò)濾用戶沒(méi)有權(quán)限看到的數(shù)據(jù)信息,這時(shí)候就需要有一個(gè)能夠修改響應(yīng)體的Filter。
Spring Cloud Gateway 版本為2.1.0
在當(dāng)前版本,ModifyRequestBodyGatewayFilterFactory是官方提供的修改響應(yīng)體的參考類,This filter is BETA and may be subject to change in a future release.,類的注釋中說(shuō)明這個(gè)類在以后版本中會(huì)改進(jìn),實(shí)際使用可以參考實(shí)現(xiàn)功能,但是性能影響較大,不過(guò)沒(méi)有別的選擇還是得選擇這個(gè)。
官方文檔:
最終代碼
先貼最終代碼
public class ResponseDecryptionGlobalFilter implements GlobalFilter, Ordered { private static Logger log = LoggerFactory.getLogger(ResponseDecryptionGlobalFilter.class); @Override public int getOrder() { // 控制在NettyWriteResponseFilter后執(zhí)行 return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { return processResponse(exchange, chain); } private Mono<Void> processResponse(ServerWebExchange exchange, GatewayFilterChain chain) { // 路由中如果不需要過(guò)濾則不進(jìn)行過(guò)濾 if (!BooleanUtils.isTrue()) { return chain.filter(exchange); } ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(exchange.getResponse()) { @Override public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { String originalResponseContentType = exchange.getAttribute(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(HttpHeaders.CONTENT_TYPE, originalResponseContentType); ResponseAdapter responseAdapter = new ResponseAdapter(body, httpHeaders); DefaultClientResponse clientResponse = new DefaultClientResponse(responseAdapter, ExchangeStrategies.withDefaults()); Mono<String> rawBody = clientResponse.bodyToMono(String.class).map(s -> s); BodyInserter<Mono<String>, ReactiveHttpOutputMessage> bodyInserter = BodyInserters.fromPublisher(rawBody, String.class); CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, exchange.getResponse().getHeaders()); return bodyInserter.insert(outputMessage, new BodyInserterContext()) .then(Mono.defer(() -> { Flux<DataBuffer> messageBody = outputMessage.getBody(); Flux<DataBuffer> flux = messageBody.map(buffer -> { CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer()); DataBufferUtils.release(buffer); // 將響應(yīng)信息轉(zhuǎn)化為字符串 String responseStr = charBuffer.toString(); if (StringUtils.isNotBlank(responseStr)) { try { JSONObject result = JSONObject.parseObject(responseStr); System.out.println(dataFilter(result)); if (result.containsKey("data")) { responseStr = dataFilter(result); } else { log.error("響應(yīng)結(jié)果序列化異常:{}", responseStr); } } catch (JSONException e) { log.error("響應(yīng)結(jié)果序列化異常:{}", responseStr); } } return getDelegate().bufferFactory().wrap(responseStr.getBytes(StandardCharsets.UTF_8)); }); HttpHeaders headers = getDelegate().getHeaders(); // 修改響應(yīng)包的大小,不修改會(huì)因?yàn)榘笮〔煌粸g覽器丟掉 flux = flux.doOnNext(data -> headers.setContentLength(data.readableByteCount())); return getDelegate().writeWith(flux); })); } }; return chain.filter(exchange.mutate().response(responseDecorator).build()); } /** * 權(quán)限數(shù)據(jù)過(guò)濾 * * @param result * @return */ private String dataFilter(JSONObject result) { Object data = result.get("data"); return result.toJSONString(); } private class ResponseAdapter implements ClientHttpResponse { private final Flux<DataBuffer> flux; private final HttpHeaders headers; @SuppressWarnings("unchecked") private ResponseAdapter(Publisher<? extends DataBuffer> body, HttpHeaders headers) { this.headers = headers; if (body instanceof Flux) { flux = (Flux) body; } else { flux = ((Mono) body).flux(); } } @Override public Flux<DataBuffer> getBody() { return flux; } @Override public HttpHeaders getHeaders() { return headers; } @Override public HttpStatus getStatusCode() { return null; } @Override public int getRawStatusCode() { return 0; } @Override public MultiValueMap<String, ResponseCookie> getCookies() { return null; } } }
響應(yīng)體報(bào)文過(guò)大: 起初直接讀取buffer的響應(yīng)信息,包小的情況沒(méi)有問(wèn)題,但是包大了會(huì)拋出json無(wú)法轉(zhuǎn)換異常,因?yàn)闆](méi)能讀取完整的響應(yīng)內(nèi)容,參考ModifyRequestBodyGatewayFilter,等待buffer全部讀完再轉(zhuǎn)為數(shù)組,然后執(zhí)行處理。本質(zhì)原因是底層的Reactor-Netty的數(shù)據(jù)塊讀取大小限制導(dǎo)致獲取到的DataBuffer實(shí)例里面的數(shù)據(jù)是不完整的。
修改響應(yīng)信息后,響應(yīng)的ContentLength會(huì)發(fā)生變化,忘記修改response中的Content-Length長(zhǎng)度,導(dǎo)致前端請(qǐng)求無(wú)法獲取修改后的響應(yīng)結(jié)果。
flux = flux.doOnNext(data -> headers.setContentLength(data.readableByteCount()));
order值必須小于-1,因?yàn)楦采w返回響應(yīng)體,自定義的GlobalFilter必須比NettyWriteResponseFilter處理完后執(zhí)行。order越小越早進(jìn)行處理,越晚處理響應(yīng)結(jié)果。
先看ServerWebExchange的注釋:
Contract for an HTTP request-response interaction. Provides access to the HTTP request and response and also exposes additional server-side processing related properties and features such as request attributes.
翻譯一下大概是:
ServerWebExchange是一個(gè)**HTTP請(qǐng)求-響應(yīng)交互的契約。**提供對(duì)HTTP請(qǐng)求和響應(yīng)的訪問(wèn),并公開(kāi)額外的服務(wù)器端處理相關(guān)屬性和特性,如請(qǐng)求屬性。
ServerWebExchange有點(diǎn)像Context的角色,我把它理解為http請(qǐng)求信息在Filter透?jìng)鞯娜萜?,之所以稱之為容器,因?yàn)樗梢源鎯?chǔ)我們像放進(jìn)去的數(shù)據(jù)。
注意:
ServerHttpRequest是一個(gè)只讀類,因此需要通過(guò)下面例子的方法來(lái)進(jìn)行修改,對(duì)于讀多寫(xiě)少的場(chǎng)景,這種設(shè)計(jì)模式是值得借鑒的
ServerHttpRequest newRequest = request.mutate().headers("key","value").path("/myPath").build(); ServerWebExchange newExchange = exchange.mutate().response(responseDecorator).build();
在gateway中修改返回的響應(yīng)體,在全局Filter中添加如下代碼:
import org.springframework.core.Ordered; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; @Component public class RequestGlobalFilter implements GlobalFilter, Ordered { //... @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { //... ResponseDecorator decorator = new ResponseDecorator(exchange.getResponse()); return chain.filter(exchange.mutate().response(decorator).build()); } @Override public int getOrder() { return -1000; } }
通過(guò).response(decorator)設(shè)置一個(gè)響應(yīng)裝飾器(自定義),以下是裝飾器具體實(shí)現(xiàn):
import cn.hutool.json.JSONObject; import org.reactivestreams.Publisher; 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 reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.nio.charset.Charset; /** * @author visy.wang * @desc 響應(yīng)裝飾器(重構(gòu)響應(yīng)體) */ public class ResponseDecorator extends ServerHttpResponseDecorator{ public ResponseDecorator(ServerHttpResponse delegate){ super(delegate); } @Override @SuppressWarnings(value = "unchecked") public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { if(body instanceof Flux) { Flux<DataBuffer> fluxBody = (Flux<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); DataBufferUtils.release(join);// 釋放掉內(nèi)存 String bodyStr = new String(content, Charset.forName("UTF-8")); //修改響應(yīng)體 bodyStr = modifyBody(bodyStr); getDelegate().getHeaders().setContentLength(bodyStr.getBytes().length); return bufferFactory().wrap(bodyStr.getBytes()); })); } return super.writeWith(body); } //重寫(xiě)這個(gè)函數(shù)即可 private String modifyBody(String jsonStr){ JSONObject json = new JSONObject(jsonStr); //TODO...修改響應(yīng)體 return json.toString(); } }
感謝各位的閱讀,以上就是“Spring Cloud Gateway怎么修改HTTP響應(yīng)信息”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)Spring Cloud Gateway怎么修改HTTP響應(yīng)信息這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。