SpringCloud gateway如何修改返回?cái)?shù)據(jù)
版本說明
| 開源軟件 | 版本 |
|---|---|
| springboot | 2.1.6.RELEASE |
| jdk | 11.0.3 |
gradle
主要引入了springboot 2.1,lombok
plugins {
id 'org.springframework.boot' version '2.1.6.RELEASE'
id 'java'
id "io.freefair.lombok" version "3.6.6"
}apply plugin: 'io.spring.dependency-management'group = 'cn.buddie.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'repositories {
mavenCentral()
}ext {
set('springCloudVersion', "Greenwich.SR2")
}dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
compile 'org.projectlombok:lombok:1.18.8'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
yaml
定義路由及過濾器 test-route路由,當(dāng)Path為/users時(shí),轉(zhuǎn)到uri中配置的鏈接http://127.0.0.1:8123/users中。使用UnionResult來過濾
spring:
cloud:
gateway:
enabled: true
routes:
- id: test-route
uri: http://127.0.0.1:8123/users
predicates:
- Path=/users
filters:
- UnionResult
filter
yaml中配置的filter名字,加“GatewayFilterFactory”,就是對(duì)應(yīng)的過濾器Java類
package cn.buddie.demo.springcloudgateway.filter;import cn.buddie.demo.springcloudgateway.model.UnionResult;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;/**
* description
*
* @author buddie.wei
* @date 2019/7/20
*/
@Component
public class UnionResultGatewayFilterFactory extends ModifyResponseBodyGatewayFilterFactory {
@Override
public GatewayFilter apply(Config config) {
return new ModifyResponseGatewayFilter(this.getConfig());
}
private Config getConfig() {
Config cf = new Config();
// Config.setRewriteFunction(Class<T> inClass, Class<R> outClass, RewriteFunction<T, R> rewriteFunction)
// inClass 原數(shù)據(jù)類型,可以指定為具體數(shù)據(jù)類型,我這里指定為Object,是為了處理多種數(shù)據(jù)類型。
// 當(dāng)然支持多接口返回多數(shù)據(jù)類型的統(tǒng)一修改,yaml中的配置,path,uri需要做相關(guān)調(diào)整
// outClass 目標(biāo)數(shù)據(jù)類型
// rewriteFunction 內(nèi)容重寫方法
cf.setRewriteFunction(Object.class, UnionResult.class, getRewriteFunction());
return cf;
} private RewriteFunction<Object, UnionResult> getRewriteFunction() {
return (exchange, resp) -> Mono.just(UnionResult.builder().requestId(exchange.getRequest().getHeaders().getFirst("cn-buddie.demo.requestId")).result(resp).build());
}
}
model
package cn.buddie.demo.springcloudgateway.model;import lombok.Builder;
import lombok.Getter;
import lombok.Setter;/**
* description
*
* @author buddie.wei
* @date 2019/7/20
*/
@Getter
@Setter
@Builder
public class UnionResult {
private String requestId;
private Object result;
}
SpringCloud gateway修改返回的響應(yīng)體
問題描述:
在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;
}
}
通過.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);
} //重寫這個(gè)函數(shù)即可
private String modifyBody(String jsonStr){
JSONObject json = new JSONObject(jsonStr);
//TODO...修改響應(yīng)體
return json.toString();
}
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Java接收和處理OpenTelemetry數(shù)據(jù)的完整指南
在現(xiàn)代分布式系統(tǒng)中,OpenTelemetry 成為了一種常見的標(biāo)準(zhǔn),用于跟蹤和監(jiān)控應(yīng)用程序的性能和行為,OTLP是 OpenTelemetry 社區(qū)定義的一種數(shù)據(jù)傳輸協(xié)議,文將介紹如何使用 Java 編寫代碼來接收和處理 OTLP 數(shù)據(jù),需要的朋友可以參考下2024-04-04
Java 并發(fā)編程:volatile的使用及其原理解析
下面小編就為大家?guī)硪黄狫ava 并發(fā)編程:volatile的使用及其原理解析。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-05-05
Spring Security之LogoutSuccessHandler注銷成功操作方式
這篇文章主要介紹了Spring Security之LogoutSuccessHandler注銷成功操作方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
使用spring oauth2框架獲取當(dāng)前登錄用戶信息的實(shí)現(xiàn)代碼
這篇文章主要介紹了使用spring oauth2框架獲取當(dāng)前登錄用戶信息的實(shí)現(xiàn)代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
java實(shí)現(xiàn)客戶信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)客戶信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-02-02
關(guān)于使用swagger整合springMVC的方法
在平時(shí)開發(fā)寫接口文檔的工作時(shí),一般都是word文檔,帶來書寫麻煩、維護(hù)麻煩的問題,比如改了源代碼忘了更新文檔、解釋不明確帶來歧義、無法在線嘗試等等,swagger可以有效解決這類問題,需要的朋友可以參考下2023-04-04
Java8新特性之lambda的作用_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
我們期待了很久lambda為java帶來閉包的概念,但是如果我們不在集合中使用它的話,就損失了很大價(jià)值。現(xiàn)有接口遷移成為lambda風(fēng)格的問題已經(jīng)通過default methods解決了,在這篇文章將深入解析Java集合里面的批量數(shù)據(jù)操作解開lambda最強(qiáng)作用的神秘面紗。2017-06-06

