Introduction to soul chapter 14 principles of plug-in springcloud
The SpringCloud microservice needs to use a registry. In this case, eureka is used. The IP port of the service is registered with Eureka, and the gateway also needs to obtain the service information from Eureka, and then construct a real URL to request SpringCloud service. The details of how to run it are not detailed here, as they were explained in chapter 5. The following is a detailed analysis of the key code of the springcloud plug-in.
The core method of the SpringCloudPlugin class removes some of the nonessential codeCopy the code
// Load balancer, injected at initialization
private final LoadBalancerClient loadBalancer;
public SpringCloudPlugin(final LoadBalancerClient loadBalancer) {
this.loadBalancer = loadBalancer;
}
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorData selector, final RuleData rule) {
// Get the requested path and other information
final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
final SpringCloudRuleHandle ruleHandle = GsonUtils.getInstance().fromJson(rule.getHandle(), SpringCloudRuleHandle.class);
final SpringCloudSelectorHandle selectorHandle = GsonUtils.getInstance().fromJson(selector.getHandle(), SpringCloudSelectorHandle.class);
// The final purpose of this code is to obtain the service ID
//loadBalancer Selects a service instance by service ID. One service instance (mainly id port)
final ServiceInstance serviceInstance = loadBalancer.choose(selectorHandle.getServiceId());
/ / construct uris
final URI uri = loadBalancer.reconstructURI(serviceInstance, URI.create(soulContext.getRealUrl()));
// Generate a real URL
String realURL = buildRealURL(uri.toASCIIString(), soulContext.getHttpMethod(), exchange.getRequest().getURI().getQuery());
// Exchange carries a real URL for subsequent requests to target services, and divide does the same. For reuse?
exchange.getAttributes().put(Constants.HTTP_URL, realURL);
//set time out.
exchange.getAttributes().put(Constants.HTTP_TIME_OUT, ruleHandle.getTimeout());
return chain.execute(exchange);
}
Copy the code
How does loadBalancer synchronize service instances registered to Eureka? Where is the block of code that actually requests a real service, and how did it get there? More on these two questions later.