ribbon is responsible for load balancing of services.
Spring cloud has two kinds of service invocation methods, one is ribbon+restTemplate, the other is feign.
ribbon is simple to use as follows:
1. Introducing Dependence
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency>
2. Insert a RestTemplate into spring boot and add the @LoadBalanced annotation
@Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); }
3. Call mode
Inject a RestTemplate where the service needs to be invoked. Write the service ID at the url, and ribbon will help us resolve it into IP and port addresses.
@RequestMapping("{userId}") public String getAll2(@PathVariable("userId") String id) { String url = "http://search-service/"+id; System.out.println(url); return restTemplate.getForObject(url, String.class);; }
4. The @LoadBalanced annotation automatically implements load balancing and service IP port parsing source tracking as follows:
The reason ribbon can achieve these functions mainly depends on LoadBalancer's interceptor. View the LoadBalancerInterceptor class
public class LoadBalancerInterceptor implements ClientHttpRequestInterceptor { private LoadBalancerClient loadBalancer; private LoadBalancerRequestFactory requestFactory; public LoadBalancerInterceptor(LoadBalancerClient loadBalancer, LoadBalancerRequestFactory requestFactory) { this.loadBalancer = loadBalancer; this.requestFactory = requestFactory; } public LoadBalancerInterceptor(LoadBalancerClient loadBalancer) { // for backwards compatibility this(loadBalancer, new LoadBalancerRequestFactory(loadBalancer)); } @Override public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException { final URI originalUri = request.getURI(); String serviceName = originalUri.getHost(); Assert.state(serviceName != null, "Request URI does not contain a valid hostname: " + originalUri); return this.loadBalancer.execute(serviceName, requestFactory.createRequest(request, body, execution)); } }
Enter the execute method, at originalUri.getHost(); then load balancing will select the corresponding service and port IP. The default ribbon load balancing strategy is
IRule DEFAULT_RULE = new Round Robin Rule (); is a linear load balancing strategy, a polling method, through the calculation of counters and models to select services.
Of course, you can change to other strategies.
Configure in the configuration file
service-name: #Service name ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #Change to a random strategy