Spring Cloud Gateway 截获请求的输入输出

介绍Spring Cloud Gateway截获请求的输入输出,主要包括Spring Cloud Gateway截获请求的输入输出使用实例、应用技巧、基本知识点总结和需要注意事项。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@Component
public class AuthGlobalFilter implements GlobalFilter , Ordered {

@Override
public int getOrder(){
return -2;
}

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

URI uri = exchange.getRequest().getURI();
try {
System.out.println(uri.toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
ServerHttpRequest request= exchange.getRequest();
if("POST".equalsIgnoreCase(request.getMethodValue())) {//判断是否为POST请求
Flux<DataBuffer> body = request.getBody();
AtomicReference<String> bodyRef = new AtomicReference<>();//缓存读取的request body信息
body.subscribe(dataBuffer -> {
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer());
DataBufferUtils.release(dataBuffer);
bodyRef.set(charBuffer.toString());
});//读取request body到缓存
String bodyStr = bodyRef.get();//获取request body
System.out.println("-----------------request body start-----------------");
System.out.println(bodyStr);//这里是我们需要做的操作
System.out.println("-----------------request body end-----------------");
DataBuffer bodyDataBuffer = stringBuffer(bodyStr);
Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);

request = new ServerHttpRequestDecorator(request) {
@Override
public Flux<DataBuffer> getBody() {
return bodyFlux;
}
};//封装我们的request
}

ServerHttpResponse originalResponse = exchange.getResponse();
DataBufferFactory bufferFactory = originalResponse.bufferFactory();
ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
if (body instanceof Flux) {
Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
return super.writeWith(fluxBody.map(dataBuffer -> {
// probably should reuse buffers
byte[] content = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(content);
//释放掉内存
DataBufferUtils.release(dataBuffer);
String s = new String(content, Charset.forName("UTF-8"));
System.out.println("-----------------response body start-----------------");
System.out.println(s);
System.out.println("-----------------response body end-----------------");
//TODO,s就是response的值,想修改、查看即可随意而为
byte[] uppedContent = new String(content, Charset.forName("UTF-8")).getBytes();
return bufferFactory.wrap(uppedContent);
}));
}
// if body is not a flux. never got there.
return super.writeWith(body);
}
};
// replace response with decorator
return chain.filter(exchange.mutate().request(request).response(decoratedResponse).build());
}
}

注意order要小于-1

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :