My blog: programmer xiaoxiao sheng, welcome to browse blog!
In the SpringCloud basics tutorial (5)- configuration center hot availability and high availability, we took an in-depth look at configuration center. This chapter will continue with an in-depth study of microservices architecture and how load balancing is done in microservices.
preface
To put it simply, the Ribbon is an open source project released by Netflix. Its main function is to provide client-side software load balancing algorithms. It can configure server categories on the client side and then poll requests for load balancing.
When a project introduces Eureka dependencies, the ribbon dependencies will be automatically introduced. Of course, we can display the ribbon dependencies. When integrated Eureka DiscoveryEnabledNIWSServerList rewrite the Ribbon service list, at com.net flix. Ribbon: Ribbon – Eureka: 2.3.0 module, we can see, Also replace IPing with NIWSDiscoveryPing:
I. Rapid use of Ribbo
In the current example, we will involve the Eureka registry, two server-providers and one server-consumer. First, we start the two service providers and register with Eureka. The service provides the following interface:
@RestController
public class RibbonController {
@RequestMapping("/sayHello")
public String sayHello(String name) {
return "hello! ,"+name; }}Copy the code
Next, the ribbon dependency is introduced in the Eureka client, which is the service consumer.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
Copy the code
Change DiscoveryClient to LoadBalancerClient. As the name implies, change DiscoveryClient to LoadBalancerClient to support load balancing. Add @enableDiscoveryClient annotation to the main class of consumer to enable the discovery service function:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class RibbonController {
@Bean
public RestTemplate restTemplate(a) {
return new RestTemplate();
}
@Autowired
private LoadBalancerClient client;
@Autowired
RestTemplate restTemplate;
@GetMapping("/sayHello")
public String sayHello(String name) {
ServiceInstance instance = client.choose("server-provider");
String res = restTemplate.
getForObject(instance.getUri().toString()
+ "sayHello? name=" + name, String.class);
return res + " from :"+ instance.getPort(); }}Copy the code
Start Eureka registry, start two service providers and one service consumer. In the Monitoring page of Eureka, we can see the following content:
Then a browser request to the service caller’s interface results in:
hello! .testfrom :9001 hello! .test from :9002
Copy the code
The 9001 and 9002 responses appear alternately, indicating that the Ribbon customer is using polling to achieve load balancing.
An easier way to do this is to modify the client calling code and add the @loadBalanced annotation to the RestTemplate, using the URL: http://server-provider/sayHello? The server provider is registered with the Eureka service name. The default algorithm for @loadBalanced is polling:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class RibbonController {
@Bean
@LoadBalanced
public RestTemplate restTemplate(a) {
return new RestTemplate();
}
@Autowired
RestTemplate restTemplate;
@GetMapping("/sayHello")
public String sayHello(String name) {
String res = restTemplate
.getForObject("http://server-provider/sayHello? name=" + name, String.class);
return res;
}
Copy the code
Through this concise way can also achieve load balancing call.
2. Advanced Configuration of the Ribbon
The Ribbon provides a simple overview of the Ribbon’s basic functions. However, the Ribbon can also be configured with more customizations. For example, we want to modify the default load balancing algorithm and customize the HTTP thread pool.
2.1 Core components of the Ribbon
In the ribbon- Loadbalancer project, there are a number of interfaces defined, among them
-
IRule: interface for polling policies.
-
ServerList: Interface that defines the methods used to get the list of servers.
-
IPing: defines the interface for checking whether services communicate well with each other.
2.2 Implementing a custom algorithm
Spring Cloud provides the default implementation for Ribbon. Of course, we can customize the polling policy and other configurations. The first choice is to add @RibbonClient annotation to your startup class on the client side.
import com.microservice.RibbonConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@RibbonClient(name = "server-provider",configuration = RibbonConfig.class)
public class ServerConsumerApplication {
public static void main(String[] args) { SpringApplication.run(ServerConsumerApplication.class, args); }}Copy the code
@RibbonClient(name = “server-provider”,= ribbonConfig.class
- Name: is the name of the service provider registered in Eureka;
- Configuration: is the configuration class we are going to customize;
Next, we create the RibbonConfig configuration class,
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** * config Ribbon */
@Configuration
public class RibbonConfig {
/** * use random polling method **@return* /
@Bean
public IRule iRule(a) {
return newRandomRule(); }}Copy the code
Note: Ensure that the package where RibbonConfig is located cannot be scanned by @ComponentScan. If the main class uses @SpringBootApplication, it is also required to avoid automatic scanning. The specific configuration is as follows:
The code for the service invocation is unchanged:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class RibbonController {
@Bean
@LoadBalanced
public RestTemplate restTemplate(a) {
return new RestTemplate();
}
@Autowired
RestTemplate restTemplate;
@GetMapping("/sayHello")
public String sayHello(String name) {
String res = restTemplate.getForObject("http://server-provider/sayHello? name=" + name, String.class);
return res;
}
Copy the code
We use the browser call interface at http://192.168.1.103:5168/sayHello? Name =test, the result is returned in a random manner;
2.3 @ RibbonClient annotation
We can modify the default implementation by specifying the configuration in @RibbonClient. For the implementation of IRule, SpringCloud has the following implementation:
-
RoundRobinRule: by default, each request is assigned to the service provider in turn.
-
AvailabilityFilteringRule: more availability filtering strategy. By default, if the RestClient fails to connect for the last three times, the instance circuits trip. Once the instance trips, it remains in this state for 30 seconds before being enabled again. If the continuous connection fails, it will become circuit trip, and the waiting time will increase exponentially;
-
WeightedResponseTimeRule: Each server is weighted according to the response time, and the longer the response time, the less weight;
-
RandomRule: a RandomRule strategy
Of course, there are other weight strategies, interested students can study the source code.
Spring Cloud provides an annotation such as @RibbonClients. It is not possible for our client to call only one provider. We can configure multiple providers for this annotation.
Third, summary
This chapter introduces the Ribbon as a client load balancer that plays an important role in microservices architecture. We have a deep understanding of the Ribbon and can also customize some configurations. I believe it is not difficult to learn microservices.
In order to share this issue, you can also pay attention to the public number: programmer Xiaoxiaosheng, pay attention to more wonderful content!
SpringCloud Basics tutorial part 1 – Microservices and SpringCloud
SpringCloud basics tutorial ii – service discovery Eureka
SpringCloud basics tutorial (3)-Eureka advanced
SpringCloud Basics tutorial (4)- Getting started with configuration Center
SpringCloud basics tutorial (5)- configuring central hot availability and high availability
SpringCloud basics tutorial (6)- load balancing Ribbon
Look forward to more exciting content…
This article is published by OpenWrite!