In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to call Ribbon in SpringCloud". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to call Ribbon in SpringCloud" can help you solve the problem.
I. brief introduction
1. What is it
Spring Cloud Ribbon is a set of client load balancing tools based on Netflix Ribbon.
To put it simply, Ribbon is an open source project released by Netflix, and its main function is to provide software load balancing algorithms and service calls on the client side.
Official document
At present, it has entered the state of maintenance and can be used as an alternative through Open Feign in the future.
Load balancer + RestTemplate to achieve load balancer call
two。 Load balancing
Load balancing (Load Balance,LB), that is, users' requests are evenly distributed to multiple services to achieve high availability of the system (HA).
Load balancing is divided into two schemes: centralized LB and in-process LB.
2.1 centralized LB
That is, an independent LB facility is used between the server and the consumer, and the device is responsible for forwarding the access request to the service provider through a certain policy.
For example, Nginx, Gateway, zuul, etc.
2.2 in-process LB
The load balancing algorithm is integrated into the consumer, and the consumer obtains the available address in the registry, and then selects a suitable server through the LB algorithm.
Ribbon belongs to in-process LB, it is just a class library, integrated in the consumer process, the consumer uses it to obtain the address provided by the server.
2. Experiment
Ribbon is integrated into spring-cloud-starter-netflix-eureka-client, you can refer to the use of eureka. On this basis, with a simple modification, service invocation and load balancing can be completed.
1. RestTemplate
Official website
Through RestTemplate, you can achieve the function of HttpClient, only need to provide it with a url and return type, you can achieve remote method calls.
1.1 add to the IOC container
First, add it to the IOC container. @ LoadBalanced means to enable load balancer.
@ Configurationpublic class ApplicationContextConfig {@ Bean @ LoadBalanced public RestTemplate restTemplate () {return new RestTemplate ();}} 1.2 RestTemplate remote call @ Slf4j@RestController@RequestMapping ("/ order") public class OrderController {@ Autowired RestTemplate restTemplate; / / get @ Value ("${payment.url}") String paymentUrl in the ioc container / / URL called remotely, saved in the configuration file, decoupled @ GetMapping ("/ payment/get/ {id}") public CommonResult getPaymentById (@ PathVariable ("id") Long id) {CommonResult result = restTemplate.getForObject (paymentUrl + "/ payment/get/" + id, CommonResult.class); / / get method call, and returned as CommonResult type log.info ("Order query Payment,id:" + id); return result;}}
You can also use the getForEntity () method to get the entire response and get what you want in the response.
@ GetMapping ("/ payment/getEntity/ {id}") public CommonResult getPaymentEntityById (@ PathVariable ("id") Long id) {ResponseEntity entity = restTemplate.getForEntity (paymentUrl + "/ payment/get/" + id, CommonResult.class); log.info ("the information obtained is:" + entity.toString ()); log.info ("the StatusCode obtained is:" + entity.getStatusCode ()); log.info ("the StatusCodeValue obtained is:" + entity.getStatusCodeValue ()) Log.info ("obtained Headers is:" + entity.getHeaders ()); if (entity.getStatusCode (). Is2xxSuccessful ()) {log.info ("query success:" + id); return entity.getBody ();} else {log.info ("query failure:" + id "); return new CommonResult (CommonResult.FAIlURE," query failure ");}}
If you use the post method, it would be nice to change get to post.
1.3 profile
Url, you can write a specific address to indicate that the address is called directly, or you can write in the service name of eureka, first get all the addresses of the service in eureka, and then select one through LB.
Payment: url: "http://CLOUD-PAYMENT-SERVICE"2. LoadBalancer
The load balancer is enabled via @ LoadBalanced. The polling algorithm is used by default, or it can be modified to other algorithms.
Class algorithm com.netflix.loadbalancer.RoundRobinRule polling, the default algorithm com.netflix.loadbalancer.RandomRule random algorithm, by generating a random number to select the server com.netflix.loadbalancer.RetryRule first according to the RoundRobinRule policy to obtain services, if it fails to obtain services, it will retry within a specified time to obtain available services WeightedResponseTimeRule expansion of RoundRobinRule, the faster the response, the greater the weight of instance selection. The easier it is to be selected, BestAvailableRule will first filter out the services that are in the circuit breaker tripping state due to multiple access failures, and then select a service AvailabilityFilteringRule with the least concurrency, first filter out the fault instances, and then select the default rules of the instance ZoneAvoidanceRule with less concurrency, compound judge the performance of the region where server is located and the availability of server server 2.1 modify the load balancing algorithm
If you want the algorithm to target only one service, you cannot put it where ComponentScan can reach it, otherwise the load balancing algorithm for all services will be modified. Therefore, it is best to create a new package outside to put the LB
@ Configurationpublic class MyRule {@ Bean public IRule rule () {return new RandomRule ();}}
On the main startup class, identify the direct mapping between the service and the algorithm
SpringBootApplication@EnableEurekaClient@RibbonClient (name = "CLOUD-PAYMENT-SERVICE", configuration = MyRule.class) public class OrderApplication80 {public static void main (String [] args) {SpringApplication.run (OrderApplication80.class, args);}}
If you find this method troublesome, you can also use the configuration file method.
CLOUD-PAYMENT-SERVICE: # Service name ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # algorithm selection 3. Load balancing algorithm source code
With the default RoundRobinRule as the source code to read, the other source code is basically similar, but modified to select the server code.
The RoundRobinRule parent class implements the interface IRule for AbstractLoadBalancerRule,AbstractLoadBalancerRule
3.1 IRulepublic interface IRule {Server choose (Object var1); / / Select server, the most important method is void setLoadBalancer (ILoadBalancer var1); ILoadBalancer getLoadBalancer ();} 3.2 AbstractLoadBalancerRule
It basically has no effect, but the common parts are extracted and implemented.
Public abstract class AbstractLoadBalancerRule implements IRule, IClientConfigAware {private ILoadBalancer lb; / / ILoadBalancer interface, the main function is to obtain the status and number of current servers, and to provide the calculated parameters public AbstractLoadBalancerRule () {} public void setLoadBalancer (ILoadBalancer lb) {this.lb = lb;} public ILoadBalancer getLoadBalancer () {return this.lb;} 3.3RoundRobinRule for the load balancing algorithm.
To put it simply, polling is implemented through a counter
Public class RoundRobinRule extends AbstractLoadBalancerRule {private AtomicInteger nextServerCyclicCounter; / / atomic class, used to hold a count to record where polled is now private static final boolean AVAILABLE_ONLY_SERVERS = true; private static final boolean ALL_SERVERS = false; private static Logger log = LoggerFactory.getLogger (RoundRobinRule.class); public RoundRobinRule () {this.nextServerCyclicCounter = new AtomicInteger (0); / / initialize} public RoundRobinRule (ILoadBalancer lb) {/ / set LoadBalancer this () This.setLoadBalancer (lb) } public Server choose (ILoadBalancer lb, Object key) {/ / the most important method, select the server and return / / below to post} private int incrementAndGetModulo (int modulo) {/ / A pair of counters to modify and return a selection value, which is the implementation of the polling algorithm / / the method of posting} public Server choose (Object key) {/ / interface In this class, another method is called to implement return this.choose (this.getLoadBalancer (), key). } public void initWithNiwsConfig (IClientConfig clientConfig) {}}
Simply put, the method is to select a server to return based on the current state.
Public Server choose (ILoadBalancer lb, Object key) {if (lb = = null) {/ / if there is no LoadBalancer, log.warn ("no load balancer"); return null;} else {Server server = null; int count = 0; while (true) {if (server = = null & & count++)
< 10) { // 尝试十次,如果还找不到server就放弃了 List reachableServers = lb.getReachableServers(); // 通过LB获取目前所有可获取的服务器 List allServers = lb.getAllServers(); // 获取实际上的所有服务器 int upCount = reachableServers.size(); // 获取目前可获得的服务器数量 int serverCount = allServers.size(); // 所有服务器的数量,这是取余的除数 if (upCount != 0 && serverCount != 0) { // 如果目前有服务器且服务器可用 int nextServerIndex = this.incrementAndGetModulo(serverCount); // 最关键的选择算法,将目前的的服务器数量放进去,返回一个选择的号码 server = (Server)allServers.get(nextServerIndex); // 根据下标将服务器取出来 if (server == null) { // 如果取出来为空,表示目前不可用,则进入下一个循环 Thread.yield(); } else { if (server.isAlive() && server.isReadyToServe()) { // 如果该服务器活着且可以被使用,则直接将其返回 return server; } server = null; } continue; } log.warn("No up servers available from load balancer: " + lb); return null; } if (count >= 10) {log.warn ("No available alive servers after 10 tries from load balancer:" + lb);} return server;}
To put it simply, take the current counter + 1, get a subscript, and return it. In order to avoid the danger of high concurrency, the method of CAS is used to set it.
Private int incrementAndGetModulo (int modulo) {int current; int next; do {current = this.nextServerCyclicCounter.get (); / / get the current value next = (current + 1)% modulo; / / + 1 take the remainder} while (! this.nextServerCyclicCounter.compareAndSet (current, next)); / / CAS, return if you succeed, and return next again if you fail } this is the end of the introduction to "how to call Ribbon in SpringCloud". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
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.