In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "the introduction and workflow of Ribbon in SpringCloud". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the introduction and workflow of Ribbon in SpringCloud.
One: what is Ribbon?
Ribbon is an open source project released by Netflix, and its main function is to provide software load balancing algorithms on the client side to connect the middle-tier services of Netflix. The Ribbon client component provides a complete set of configuration items such as connection timeout, retry, etc. To put it simply, all the machines after Load Balancer (LB) are listed in the configuration file, and Ribbon will automatically help you connect these machines based on certain rules (such as simple polling, immediate connection, etc.). We can also easily implement custom load balancing algorithms using Ribbon.
II: LB scheme classification
At present, the mainstream LB schemes can be divided into two categories: one is centralized LB, which uses a separate LB facility (either hardware, such as F5, or software, such as nginx) between the consumer and provider of the service, which is responsible for forwarding access requests to the provider of the service through a certain policy. The other is in-process LB, which integrates LB logic into the consumer, who learns which addresses are available from the service registry, and then selects a suitable server from those addresses. Ribbon belongs to the latter, it is just a class library, integrated into the consumer process, consumers use it to obtain the address of the service provider.
Three: the main components and workflow of Ribbon
The core components of Ribbon, all of which are interface types, are as follows:
ServerList
Used to get the address list. It can be either static (providing a fixed set of addresses) or dynamic (the address list is queried periodically from the registry).
ServerListFilter
Used only when using dynamic ServerList to overworry about some addresses in the original list of services using a certain policy.
IRule
Select a final service address as the LB result. Selection strategies include polling, weighting based on response time, circuit breakers (when Hystrix is available), and so on.
When working, Ribbon will first get the list of all available services through ServerList, then worry about some of the addresses through ServerListFilter, and finally select a server through IRule as the final result.
Fourth: introduction to the main load balancing strategies provided by Ribbon
1: simple polling load balancer (RoundRobin)
In the way of polling, the requests are dispatched to different servers in turn, that is, each scheduling execution I = (I + 1) mod n, and select the I server.
2: random load balancing (Random)
Randomly select Server with a status of UP
3: weighted response time load balancing (WeightedResponseTime)
Assign a weight according to the corresponding time, and the longer the corresponding time is, the smaller the weight is, and the less likely it is to be selected.
4: region-aware polling load balancer (ZoneAvoidanceRule)
Compound judge the performance of server region and the availability of server choose server
Comparison of load balancing Strategies with Ribbon
Policy name Policy statement Policy description implementation description BestAvailableRulepublic class BestAvailableRule extends ClientConfigEnabledRoundRobinRule selects a minimum concurrent request server to examine the Server one by one, and if the Server is tripped, ignore it. In selecting the serverAvailabilityFilteringRulepublic class AvailabilityFilteringRule extends PredicateBasedRule with the smallest ActiveRequestsCount, filter out the back-end server marked as circuit tripped because the connection has failed, and filter out those highly concurrent back-end server (active connections exceeds the configured threshold) use an AvailabilityPredicate to include the logic of filtering server In fact, it is to check the running status of each server recorded in status. WeightedResponseTimeRulepublic class WeightedResponseTimeRule extends RoundRobinRule allocates a weight according to the corresponding time. The longer the corresponding time is, the smaller the weight is, and the less likely it is to be selected. A background thread periodically reads the evaluation response time from the status and calculates a weight for each server. The calculation of Weight is also relatively simple. Responsetime minus the average responsetime of each server is the weight of server. When you just start running and no statas is formed, use the roubine policy to select server. RetryRulepublic class RetryRule extends AbstractLoadBalancerRule retries the mechanism on the selected load balancing strategy. When selecting server is not successful within a configuration period, try to use subRule to select an available serverRoundRobinRulepublic class RoundRobinRule extends AbstractLoadBalancerRuleroundRobin polling index, select the serverRandomRulepublic class RandomRule extends AbstractLoadBalancerRule corresponding to the index, randomly select a server on the index, select the serverZoneAvoidanceRulepublic class ZoneAvoidanceRule extends PredicateBasedRule compound at the corresponding location of the index to judge the performance of the region where the server is located and the availability of the server. Select server to use ZoneAvoidancePredicate and AvailabilityPredicate to determine whether to select a server. The previous decision determines whether the operational performance of a zone is available, excluding unavailable zone (all server), and AvailabilityPredicate is used to filter out Server with too many connections.
Five: Ribbon is used alone
Create a maven project name ribbon_client
Pom content
Com.netflix.ribbon ribbon-core 2.2.0 com.netflix.ribbon ribbon-httpclient 2.2.0
Sample-client.properties profile
# Max number of retries sample-client.ribbon.MaxAutoRetries=1# Max number of next servers to retry (excluding the first server) sample-client.ribbon.MaxAutoRetriesNextServer=1# Whether all operations can be retried for this client sample-client.ribbon.OkToRetryOnAllOperations=true # Interval to refresh the server list from the source sample-client.ribbon.ServerListRefreshInterval=2000# Connect timeout used by Apache HttpClient sample-client.ribbon.ConnectTimeout=3000# Read timeout used by Apache HttpClient sample-client.ribbon.ReadTimeout=3000# Initial list of servers, can be changed via Archaius dynamic property at runtime sample-client.ribbon.listOfServers=www.sohu.com:80 Www.163.com:80,www.sina.com.cn:80sample-client.ribbon.EnablePrimeConnections=true
RibbonMain code
Import java.net.URI;import com.netflix.client.ClientFactory;import com.netflix.client.http.HttpRequest;import com.netflix.client.http.HttpResponse;import com.netflix.config.ConfigurationManager;import com.netflix.loadbalancer.ZoneAwareLoadBalancer;import com.netflix.niws.client.http.RestClient;public class RibbonMain {public static void main (String [] args) throws Exception {ConfigurationManager.loadPropertiesFromResources ("sample-client.properties"); System.out.println (ConfigurationManager.getConfigInstance () .getProperty ("sample-client.ribbon.listOfServers")) RestClient client = (RestClient) ClientFactory.getNamedClient ("sample-client"); HttpRequest request = HttpRequest.newBuilder (). Uri (new URI ("/")). Build (); for (int I = 0; I < 4; I + +) {HttpResponse response = client.executeWithLoadBalancer (request); System.out.println ("Status for URI:" + response.getRequestedURI () + "is:" + response.getStatus ());} ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer () System.out.println (lb.getLoadBalancerStats ()); ConfigurationManager.getConfigInstance (). SetProperty ("sample-client.ribbon.listOfServers", "ccblog.cn:80,www.linkedin.com:80"); System.out.println ("changing servers..."); Thread.sleep (3000); for (int I = 0; I < 3; I + +) {HttpResponse response = client.executeWithLoadBalancer (request) System.out.println ("Status for URI:" + response.getRequestedURI () + "is:" + response.getStatus ());} System.out.println (lb.getLoadBalancerStats ());}}
Code parsing
Use Archaius ConfigurationManager to load properties
Create clients and load balancers using ClientFactory
Use builder to build the http request. Note that we only support the path of the "/" part of URI. Once the server is selected by the load balancer, the complete URI will be calculated by the client.
Call API client.executeWithLoadBalancer (), not exeucte () API
Dynamically fix the server pool in the configuration
Wait for the server list to refresh (the refresh interval defined in the configuration file is 3 seconds)
Print out the server statistics recorded by the load balancer.
Six: Ribbon is used in conjunction with eureka
First start the eureka_register_service project (registry) and the biz-service-0 project (service producer)
Create maven project eureka_ribbon_client. The project startup and related configuration depend on eureka_register_service and biz-service-0.
Pom joining
Org.springframework.boot spring-boot-starter-parent 1.4.3.RELEASE org.springframework.cloud spring-cloud-starter-ribbon org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies Brixton.RELEASE pom import
In the application main class, add the discovery service capability through the @ EnableDiscoveryClient annotation. Create a RestTemplate instance and enable the load balancing capacity through the @ LoadBalanced annotation.
@ SpringBootApplication@EnableDiscoveryClientpublic class RibbonApplication {@ Bean @ LoadBalanced RestTemplate restTemplate () {return new RestTemplate ();} public static void main (String [] args) {SpringApplication.run (RibbonApplication.class, args);}}
Create a ConsumerController to consume biz-service-0 's getuser service. Invoke the service through the direct RestTemplate
@ RestControllerpublic class ConsumerController {@ Autowired RestTemplate restTemplate; @ RequestMapping (value = "/ getuserinfo", method = RequestMethod.GET) public String add () {return restTemplate.getForEntity ("http://biz-service-0/getuser", String.class) .getBody ();}}
Configure the eureka service registry in application.properties
Spring.application.name=ribbon-consumerserver.port=8003eureka.client.serviceUrl.defaultZone= http://localhost:8000/eureka/
When you are finished, you can open http://localhost:8003/getuserinfo and see the result.
Summary: Ribbon is actually a client component of soft load balancing, which can be used in conjunction with other required clients, and eureka is just one of them.
At this point, I believe you have a deeper understanding of the "introduction and workflow of Ribbon in SpringCloud". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.