您好,登錄后才能下訂單哦!
這篇文章主要講解了“Spring Cloud Gateway怎么修改HTTP響應信息”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Spring Cloud Gateway怎么修改HTTP響應信息”吧!
實踐Spring Cloud的過程中,使用Gateway作為路由組件,并且基于Gateway實現權限的驗證、攔截、過濾,對于下游微服務的響應結果,我們總會有需要修改以統一數據格式,或者修改過濾用戶沒有權限看到的數據信息,這時候就需要有一個能夠修改響應體的Filter。
Spring Cloud Gateway 版本為2.1.0
在當前版本,ModifyRequestBodyGatewayFilterFactory是官方提供的修改響應體的參考類,This filter is BETA and may be subject to change in a future release.,類的注釋中說明這個類在以后版本中會改進,實際使用可以參考實現功能,但是性能影響較大,不過沒有別的選擇還是得選擇這個。
官方文檔:
最終代碼
先貼最終代碼
public class ResponseDecryptionGlobalFilter implements GlobalFilter, Ordered { private static Logger log = LoggerFactory.getLogger(ResponseDecryptionGlobalFilter.class); @Override public int getOrder() { // 控制在NettyWriteResponseFilter后執行 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) { // 路由中如果不需要過濾則不進行過濾 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); // 將響應信息轉化為字符串 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("響應結果序列化異常:{}", responseStr); } } catch (JSONException e) { log.error("響應結果序列化異常:{}", responseStr); } } return getDelegate().bufferFactory().wrap(responseStr.getBytes(StandardCharsets.UTF_8)); }); HttpHeaders headers = getDelegate().getHeaders(); // 修改響應包的大小,不修改會因為包大小不同被瀏覽器丟掉 flux = flux.doOnNext(data -> headers.setContentLength(data.readableByteCount())); return getDelegate().writeWith(flux); })); } }; return chain.filter(exchange.mutate().response(responseDecorator).build()); } /** * 權限數據過濾 * * @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; } } }
響應體報文過大: 起初直接讀取buffer的響應信息,包小的情況沒有問題,但是包大了會拋出json無法轉換異常,因為沒能讀取完整的響應內容,參考ModifyRequestBodyGatewayFilter,等待buffer全部讀完再轉為數組,然后執行處理。本質原因是底層的Reactor-Netty的數據塊讀取大小限制導致獲取到的DataBuffer實例里面的數據是不完整的。
修改響應信息后,響應的ContentLength會發生變化,忘記修改response中的Content-Length長度,導致前端請求無法獲取修改后的響應結果。
flux = flux.doOnNext(data -> headers.setContentLength(data.readableByteCount()));
order值必須小于-1,因為覆蓋返回響應體,自定義的GlobalFilter必須比NettyWriteResponseFilter處理完后執行。order越小越早進行處理,越晚處理響應結果。
先看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是一個**HTTP請求-響應交互的契約。**提供對HTTP請求和響應的訪問,并公開額外的服務器端處理相關屬性和特性,如請求屬性。
ServerWebExchange有點像Context的角色,我把它理解為http請求信息在Filter透傳的容器,之所以稱之為容器,因為它可以存儲我們像放進去的數據。
注意:
ServerHttpRequest是一個只讀類,因此需要通過下面例子的方法來進行修改,對于讀多寫少的場景,這種設計模式是值得借鑒的
ServerHttpRequest newRequest = request.mutate().headers("key","value").path("/myPath").build(); ServerWebExchange newExchange = exchange.mutate().response(responseDecorator).build();
在gateway中修改返回的響應體,在全局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; } }
通過.response(decorator)設置一個響應裝飾器(自定義),以下是裝飾器具體實現:
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 響應裝飾器(重構響應體) */ 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);// 釋放掉內存 String bodyStr = new String(content, Charset.forName("UTF-8")); //修改響應體 bodyStr = modifyBody(bodyStr); getDelegate().getHeaders().setContentLength(bodyStr.getBytes().length); return bufferFactory().wrap(bodyStr.getBytes()); })); } return super.writeWith(body); } //重寫這個函數即可 private String modifyBody(String jsonStr){ JSONObject json = new JSONObject(jsonStr); //TODO...修改響應體 return json.toString(); } }
感謝各位的閱讀,以上就是“Spring Cloud Gateway怎么修改HTTP響應信息”的內容了,經過本文的學習后,相信大家對Spring Cloud Gateway怎么修改HTTP響應信息這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。