Ribbon 负载均衡调用04——ribbon 负载均衡算法||手写轮询算法(原理+JUC)CAS+自旋锁
生活随笔
收集整理的這篇文章主要介紹了
Ribbon 负载均衡调用04——ribbon 负载均衡算法||手写轮询算法(原理+JUC)CAS+自旋锁
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
RoundRobinRule.java? 源碼剖析
/*** Copyright 2013 Netflix, Inc.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.**/ package com.netflix.loadbalancer;import com.netflix.client.config.IClientConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import java.util.List; import java.util.concurrent.atomic.AtomicInteger;/*** The most well known and basic load balancing strategy, i.e. Round Robin Rule.** @author stonse* @author Nikos Michalakis <nikos@netflix.com>**/ public class RoundRobinRule extends AbstractLoadBalancerRule {private AtomicInteger nextServerCyclicCounter;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() {nextServerCyclicCounter = new AtomicInteger(0);}public RoundRobinRule(ILoadBalancer lb) {this();setLoadBalancer(lb);}public Server choose(ILoadBalancer lb, Object key) {if (lb == null) {log.warn("no load balancer");return null;}Server server = null;int count = 0;while (server == null && count++ < 10) {List<Server> reachableServers = lb.getReachableServers();List<Server> allServers = lb.getAllServers();int upCount = reachableServers.size();int serverCount = allServers.size();if ((upCount == 0) || (serverCount == 0)) {log.warn("No up servers available from load balancer: " + lb);return null;}int nextServerIndex = incrementAndGetModulo(serverCount);server = allServers.get(nextServerIndex);if (server == null) {/* Transient. */Thread.yield();continue;}if (server.isAlive() && (server.isReadyToServe())) {return (server);}// Next.server = null;}if (count >= 10) {log.warn("No available alive servers after 10 tries from load balancer: "+ lb);}return server;}/*** Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.** @param modulo The modulo to bound the value of the counter.* @return The next value.*/private int incrementAndGetModulo(int modulo) {for (;;) {int current = nextServerCyclicCounter.get();int next = (current + 1) % modulo;if (nextServerCyclicCounter.compareAndSet(current, next))return next;}}@Overridepublic Server choose(Object key) {return choose(getLoadBalancer(), key);}@Overridepublic void initWithNiwsConfig(IClientConfig clientConfig) {} }LoadBalancer.java
package com.dym.springcloud.lb;import org.springframework.cloud.client.ServiceInstance;import java.util.List;public interface LoadBalancer {ServiceInstance instances(List<ServiceInstance> serviceInstances); }MyLB.java
package com.dym.springcloud.lb;import org.springframework.cloud.client.ServiceInstance; import org.springframework.stereotype.Component;import java.util.List; import java.util.concurrent.atomic.AtomicInteger;@Component public class MyLB implements LoadBalancer {private AtomicInteger atomicInteger = new AtomicInteger(0);public final int getAndIncrement(){int current;int next;do {current = this.atomicInteger.get();next = current >= 2147483647 ? 0 : current + 1;}while(!this.atomicInteger.compareAndSet(current,next));System.out.println("*****第幾次訪問,次數next: "+next);return next;}//負載均衡算法:rest接口第幾次請求數 % 服務器集群總數量 = 實際調用服務器位置下標 ,每次服務重啟動后rest接口計數從1開始。@Overridepublic ServiceInstance instances(List<ServiceInstance> serviceInstances){int index = getAndIncrement() % serviceInstances.size();return serviceInstances.get(index);} }OrderController.java
package com.dym.springcloud.controller;import com.dym.springcloud.entities.CommonResult; import com.dym.springcloud.entities.Payment; import com.dym.springcloud.lb.LoadBalancer; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate;import javax.annotation.Resource; import java.net.URI; import java.util.List;@RestController @Slf4j public class OrderController {//public static final String PAYMENT_URL = "http://localhost:8001";public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";@Resourceprivate RestTemplate restTemplate;@Resourceprivate LoadBalancer loadBalancer;@Resourceprivate DiscoveryClient discoveryClient;@GetMapping("/consumer/payment/create")public CommonResult<Payment> create(Payment payment){return restTemplate.postForObject(PAYMENT_URL +"/payment/create",payment,CommonResult.class);}@GetMapping("/consumer/payment/get/{id}")public CommonResult<Payment> getPayment(@PathVariable("id") Long id){return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);}@GetMapping("/consumer/payment/getForEntity/{id}")public CommonResult<Payment> getPayment2(@PathVariable("id") Long id){ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);if(entity.getStatusCode().is2xxSuccessful()){return entity.getBody();}else{return new CommonResult<>(444,"操作失敗");}}@GetMapping(value = "/consumer/payment/lb")public String getPaymentLB(){List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");if(instances == null || instances.size() <= 0){return null;}ServiceInstance serviceInstance = loadBalancer.instances(instances);URI uri = serviceInstance.getUri();return restTemplate.getForObject(uri+"/payment/lb",String.class);}}?
總結
以上是生活随笔為你收集整理的Ribbon 负载均衡调用04——ribbon 负载均衡算法||手写轮询算法(原理+JUC)CAS+自旋锁的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ribbon 负载均衡调用01——概述
- 下一篇: Consul 服务注册与发现01——简介