use of org.apache.servicecomb.loadbalance.LoadBalancer in project java-chassis by ServiceComb.
the class CommonHttpEdgeDispatcher method onRequest.
protected void onRequest(RoutingContext context) {
URLMappedConfigurationItem configurationItem = findConfigurationItem(context.request().uri());
if (configurationItem == null) {
context.next();
return;
}
String uri = Utils.findActualPath(context.request().uri(), configurationItem.getPrefixSegmentCount());
Invocation invocation = new Invocation() {
@Override
public String getConfigTransportName() {
return "rest";
}
@Override
public String getMicroserviceName() {
return configurationItem.getMicroserviceName();
}
};
LoadBalancer loadBalancer = getOrCreateLoadBalancer(invocation, configurationItem.getMicroserviceName(), configurationItem.getVersionRule());
ServiceCombServer server = loadBalancer.chooseServer(invocation);
if (server == null) {
LOG.warn("no available server for service {}", configurationItem.getMicroserviceName());
serverNotReadyResponse(context);
return;
}
URIEndpointObject endpointObject = new URIEndpointObject(server.getEndpoint().getEndpoint());
RequestOptions requestOptions = new RequestOptions();
requestOptions.setHost(endpointObject.getHostOrIp()).setPort(endpointObject.getPort()).setSsl(endpointObject.isSslEnabled()).setMethod(context.request().method()).setURI(uri);
HttpClient httpClient;
if (endpointObject.isHttp2Enabled()) {
httpClient = HttpClients.getClient(Http2TransportHttpClientOptionsSPI.CLIENT_NAME, false).getHttpClient();
} else {
httpClient = HttpClients.getClient(HttpTransportHttpClientOptionsSPI.CLIENT_NAME, false).getHttpClient();
}
context.request().pause();
httpClient.request(requestOptions).compose(httpClientRequest -> {
context.request().headers().forEach((header) -> httpClientRequest.headers().set(header.getKey(), header.getValue()));
context.request().resume();
context.request().handler(httpClientRequest::write);
context.request().endHandler((v) -> httpClientRequest.end());
return httpClientRequest.response().compose(httpClientResponse -> {
context.response().setStatusCode(httpClientResponse.statusCode());
httpClientResponse.headers().forEach((header) -> context.response().headers().set(header.getKey(), header.getValue()));
httpClientResponse.handler(this.responseHandler(context));
httpClientResponse.endHandler((v) -> context.response().end());
return Future.succeededFuture();
});
}).onFailure(failure -> {
LOG.warn("send request to target {}:{} failed, cause {}", endpointObject.getHostOrIp(), endpointObject.getPort(), failure.getMessage());
serverNotReadyResponse(context);
});
}
Aggregations