SpringCloud 2020-Ribbon負(fù)載均衡服務(wù)調(diào)用的實現(xiàn)
1、概述

官網(wǎng):https://github.com/Netflix/ribbon/wiki/Getting-Started
Ribbon目前也進(jìn)入維護(hù)模式,未來替換方案:
LB(負(fù)載均衡)

集中式LB

進(jìn)程內(nèi)LB

Ribbon就是負(fù)載均衡+RestTemplate調(diào)用
2、Ribbon負(fù)載均衡演示
1、架構(gòu)說明

總結(jié):Ribbon其實就是一個軟負(fù)載均衡的客戶端組件,他可以和其他所需請求的客戶端結(jié)合使用,和eureka結(jié)合只是其中的一個實例。
2、


3、二說RestTemplate的使用
官網(wǎng)
修改cloud-consumer-order80
getForObject方法/getForEntity方法

postForObject/postForEntity

- GET請求方法
- POST請求方法
4、依次2啟動7001,7002,8001,8002,80。訪問:http://localhost/consumer/payment/getForEntity/31
3、Ribbon核心組件IRule
IRule:根據(jù)特定算法從服務(wù)列表中選取一個要訪問的服務(wù)

Ribbon自帶負(fù)載均衡算法:

如何替換負(fù)載均衡算法:修改cloud-consumer-order80
1、注意配置細(xì)節(jié)

2、新建package

3、在myrule下面新建配置類MySelfRule
package com.liukai.myrule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author liukai
* @version 1.0.0
* @ClassName MySelfRule.java
* @Description TODO
* @createTime 2021年03月21日 11:50:00
*/
@Configuration
public class MySelfRule {
@Bean(name = "myRandomRule")
public IRule myRule(){
return new RandomRule();//定義為隨機(jī)
}
}
4、主啟動類添加@RibbonClient
package com.liukai.springcloud;
import com.liukai.myrule.MySelfRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
/**
* @author liukai
* @version 1.0.0
* @ClassName OrderMain80.java
* @Description TODO
* @createTime 2021年03月19日 18:27:00
*/
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class);
}
}
5、測試:依次啟動7001,7002,8001,8002,cloud-consumer-order80
訪問:http://localhost/consumer/payment/get/31
多方問幾次,可以發(fā)現(xiàn)查詢的端口號是隨機(jī)的,而不是交替出現(xiàn)了

4、Ribbon負(fù)載均衡算法
4.1 原理 + 源碼
1、注釋掉cloud-consumer-order80主啟動類的@RibbonClient
2、原理

3、源碼:
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;
}
}
4.2 手寫負(fù)載均衡算法
1、修改8001,8002的controller
// 手寫負(fù)載均衡需要用到
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
return serverPort;
}
2、cloud-consumer-order80的ApplicationContextBean去掉@LoadBalanced
3、新建接口LoadBalancer
package com.liukai.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
/**
* @author liukai
* @version 1.0.0
* @ClassName LoadBalancer.java
* @Description TODO
* @createTime 2021年03月21日 12:24:00
*/
public interface LoadBalancer {
//收集服務(wù)器總共有多少臺能夠提供服務(wù)的機(jī)器,并放到list里面
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
4、新建實現(xiàn)類MyLB
package com.liukai.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author liukai
* @version 1.0.0
* @ClassName MyLB.java
* @Description TODO
* @createTime 2021年03月21日 12:27:00
*/
@Component
public class MyLB implements LoadBalancer {
private AtomicInteger atomicInteger = new AtomicInteger(0);
//坐標(biāo)
private final int getAndIncrement() {
int current;
int next;
do {
current = this.atomicInteger.get();
next = current >= 2147483647 ? 0 : current + 1;
} while (!this.atomicInteger.compareAndSet(current, next)); //第一個參數(shù)是期望值,第二個參數(shù)是修改值是
System.out.print("*******第幾次訪問,次數(shù)next: " + next);
return next;
}
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) { //得到機(jī)器的列表
int index = getAndIncrement() % serviceInstances.size(); //得到服務(wù)器的下標(biāo)位置
System.out.println(" ====>端口:" + serviceInstances.get(index).getPort());
return serviceInstances.get(index);
}
}
5、修改OrderController
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
@GetMapping(value = "/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if (instances == null || instances.size() <= 0){
return null;
}
// instances.forEach(System.out::println);
// 使用手寫的負(fù)載均衡算法獲取服務(wù)
ServiceInstance serviceInstance = loadBalancer.instances(instances);
// 獲取服務(wù)的地址
URI uri = serviceInstance.getUri();
// 拼接地址訪問
return restTemplate.getForObject(uri+"/payment/lb",String.class);
}
6、測試:訪問 http://localhost/consumer/payment/lb
發(fā)現(xiàn)訪問的端口號開始輪詢出現(xiàn),手寫負(fù)載均衡輪詢算法成功


到此這篇關(guān)于SpringCloud 2020-Ribbon負(fù)載均衡服務(wù)調(diào)用的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringCloud Ribbon負(fù)載均衡內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JAVA使用爬蟲抓取網(wǎng)站網(wǎng)頁內(nèi)容的方法
這篇文章主要介紹了JAVA使用爬蟲抓取網(wǎng)站網(wǎng)頁內(nèi)容的方法,實例分析了java爬蟲的兩種實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07
JavaMail實現(xiàn)發(fā)送超文本(html)格式郵件的方法
這篇文章主要介紹了JavaMail實現(xiàn)發(fā)送超文本(html)格式郵件的方法,實例分析了java發(fā)送超文本文件的相關(guān)技巧,需要的朋友可以參考下2015-05-05
Java亂碼問題解決方法_動力節(jié)點(diǎn)Java學(xué)院整理
開發(fā)java應(yīng)用出現(xiàn)亂碼是很常見的,畢竟現(xiàn)在unicode的使用還不是很廣泛,下面給大家分享Java亂碼問題解決方法,感興趣的朋友一起看看吧2017-07-07


