谈不上核心分析
gateway 网关,本质是实现一层反向代理,client提交 获取request,提交给upstream 把upstream 返回的response 返回给client
查看spring-cloud-gateway的反向代理的实现位置
spring-cloud-gateway 提供两种方式的代理,传统的bio,spirng-mvc/serverlet/jetty, 最新的nio,spring webflux/netty
以最简单的get请求为例
对bio包spring-cloud-gateway-mvc
核心类
public class ProxyExchange<T> {
...
private RestTemplate rest;
public ResponseEntity<T> get() {
RequestEntity<?> requestEntity = headers((BodyBuilder) RequestEntity.get(uri)).build();
return exchange(requestEntity);
}
private ResponseEntity<T> exchange(RequestEntity<?> requestEntity) {
Type type = this.responseType;
if (type instanceof TypeVariable || type instanceof WildcardType) {
type = Object.class;
}
return rest.exchange(requestEntity, ParameterizedTypeReference.forType(responseType));
}
}
关键是rest
package org.springframework.web.client;
public class RestTemplate extends InterceptingHttpAccessor implements RestOperations {
对nio 结构类似
包spring-cloud-gateway-webflux
public class ProxyExchange<T> {
private WebClient rest;
public Mono<ResponseEntity<T>> get() {
RequestEntity<?> requestEntity = headers((BodyBuilder) RequestEntity.get(uri)).build();
return exchange(requestEntity);
}
private Mono<ResponseEntity<T>> exchange(RequestEntity<?> requestEntity) {
Type type = this.responseType;
RequestBodySpec builder = rest.method(requestEntity.getMethod()).uri(requestEntity.getUrl())
.headers(headers -> addHeaders(headers, requestEntity.getHeaders()));
Mono<ClientResponse> result;
if (requestEntity.getBody() instanceof Publisher) {
@SuppressWarnings("unchecked")
Publisher<Object> publisher = (Publisher<Object>) requestEntity.getBody();
result = builder.body(publisher, Object.class).exchange();
}
else if (requestEntity.getBody() != null) {
result = builder.body(BodyInserters.fromValue(requestEntity.getBody())).exchange();
}
else {
if (hasBody) {
result = builder.headers(headers -> addHeaders(headers, exchange.getRequest().getHeaders()))
.body(exchange.getRequest().getBody(), DataBuffer.class).exchange();
}
else {
result = builder.headers(headers -> addHeaders(headers, exchange.getRequest().getHeaders())).exchange();
}
}
return result.flatMap(response -> response.toEntity(ParameterizedTypeReference.forType(type)));
}
}
rest
package org.springframework.web.reactive.function.client;
public interface WebClient {}
class DefaultWebClient implements WebClient {
...
}