当前位置:网站首页>Ribbon核心源码解析
Ribbon核心源码解析
2022-06-28 09:56:00 【InfoQ】
spring.factories- 在spring-cloud-common中,存在自动配置类
LoadBalancerAutoConfiguration
- 在eureka-client中,存在配置类
RibbonEurekaAutoConfiguration
- 在ribbon中,存在配置类
RibbonAutoConfiguration
RibbonEurekaAutoConfiguration@AutoConfigureAfterRibbonAutoConfiguration调用流程
RestTemplate@LoadBalanced@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
@GetMapping("/test")
public String test(String service){
String result=restTemplate.getForObject("http://eureka-hi/"+service,String.class);
System.out.println(result);
return result;
}
RestTemplate@LoadBalanced/**
* Annotation to mark a RestTemplate bean to be configured to use a LoadBalancerClient
* @author Spencer Gibb
*/
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Qualifier
public @interface LoadBalanced {
}
@LoadBalancedRestTemplate@LoadBalancedLoadBalancerAutoConfigurationLoadBalancerInterceptorrestTemplaterestTemplateinterceptinterceptRibbonLoadBalancerClientexecuteILoadBalancerchooseServerILoadBalancerexecuteapplyLoadBalancerContextreconstructURIWithServerurlurlAbstractClientHttpRequestexecuteexecuteInternalRestTemplateHttpURLConnection负载均衡过程
LoadBalancerClient@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/choose")
public String loadBalance(String serviceId){
ServiceInstance instance = loadBalancerClient.choose(serviceId);
System.out.println(instance.getHost()+" "+instance.getPort());
return "ok";
}
LoadBalancerClientchooseLoadBalancerClientRibbonLoadBalancerClientchoosgetServerloadBalancerZoneAwareLoadBalancerallServerListchooseServerzoneBaseLoadBalancerchooseServerIRuleIRuleZoneAvoidanceRuleIRuleZoneAvoidanceRulechoosePredicateBasedRulechooseAbstractServerPredicatechooseRoundRobinAfterFilteringchooseILoadBalancer核心组件ILoadBalancer
LoadBalancergetServergetLoadBalancerILoadBalancerBeanFactoryUtilgetBeangetServerZoneAwareLoadBalancerILoadBalancerpublic interface ILoadBalancer {
//往该ILoadBalancer中添加服务
public void addServers(List<Server> newServers);
//选择一个可以调用的实例,keyb不是服务名称,而是zone的id
public Server chooseServer(Object key);
//标记下线服务
public void markServerDown(Server server);
@Deprecated
public List<Server> getServerList(boolean availableOnly);
//获取可用服务列表
public List<Server> getReachableServers();
//获取所有服务列表
public List<Server> getAllServers();
}
ILoadBalancerIRule服务获取
RibbonEurekaAutoConfiguration@Configuration
@EnableConfigurationProperties
@ConditionalOnRibbonAndEurekaEnabled
@AutoConfigureAfter(RibbonAutoConfiguration.class)
@RibbonClients(defaultConfiguration = EurekaRibbonClientConfiguration.class)
public class RibbonEurekaAutoConfiguration {
}
EurekaRibbonClientConfigurationribbonServerListDiscoveryEnabledNIWSServerListDiscoveryEnabledNIWSServerListServerListServerListpublic interface ServerList<T extends Server> {
public List<T> getInitialListOfServers();
public List<T> getUpdatedListOfServers();
}
DiscoveryEnabledNIWSServerListobtainServersViaDiscoveryEurekaClientEurekaClientUPserverListserverListDynamicServerListLoadBalancersetServerListBaseLoadBalancersetServersListBaseLoadBalancerprotected volatile List<Server> allServerList = Collections.synchronizedList(new ArrayList<Server>());
protected volatile List<Server> upServerList = Collections.synchronizedList(new ArrayList<Server>());
setServersListserverListallServerListZoneAwareLoadBalancerBaseLoadBalancersetupPingTaskpingrunPingerSerialPingStrategypingServerspingServersNIWSDiscoveryPingisAliveNIWSDiscoveryPingIPingIPingisAlivepublic interface IPing {
public boolean isAlive(Server server);
}
NIWSDiscoveryPingisAliveserverListUPPingerrunPinggerchangedServersnewUpListupServerListchangedServersresultsresultsBaseLoadBalancersetServersListIPingPollingServerListUpdaterstartBaseLoadBalancersetServersListIPing- 更新列表
- ping机制
服务选取
IRulepublic interface IRule{
public Server choose(Object key);
public void setLoadBalancer(ILoadBalancer lb);
public ILoadBalancer getLoadBalancer();
}
chooseIRuleZoneAvoidanceRulezoneIRulechoose@BeanIRuleIRuleIRuleComponentScan@RibbonClients@RibbonClients({@RibbonClient(name="eureka-hi",configuration = HiRuleConfig.class),
@RibbonClient(name = "eureka-test",configuration = TestRuleConfig.class)})
public class ServiceFeignApplication {
……
}
总结
- 拦截请求,通过请求中的url地址,截取服务名称
- 通过
LoadBalancerClient获取ILoadBalancer
- 使用Eureka获取服务列表
- 通过
IRule负载均衡策略选择具体服务
ILoadBalancer通过IPing及定时更新机制来维护服务列表
- 重构该url地址,最终调用
HttpURLConnection发起请求
边栏推荐
- Custom exception classes and exercises
- Summary of MySQL basic knowledge points
- 使用 ABAP 操作 Excel 的几种方法
- On the influence of small program on the digitalization of media industry
- 接口自动化框架脚手架-利用反射机制实现接口统一发起端
- Decorator
- Composite pattern
- Methods for creating multithreads ---1 creating subclasses of thread class and multithreading principle
- 各位大佬,问下Mysql不支持EARLIEST_OFFSET模式吗?Unsupported star
- bad zipfile offset (local header sig)
猜你喜欢

Caffeine cache, the king of cache, has stronger performance than guava

idea连接sql sever失败
![[Unity]EBUSY: resource busy or locked](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[Unity]EBUSY: resource busy or locked

Application of X6 in data stack index management

组合模式(Composite Pattern)
![[happy Lantern Festival] guessing lantern riddles eating lantern festival full of vitality ~ (with lantern riddle guessing games)](/img/04/454bede0944f56ba69cddf6b237392.jpg)
[happy Lantern Festival] guessing lantern riddles eating lantern festival full of vitality ~ (with lantern riddle guessing games)
![[NLP] this year's college entrance examination English AI score is 134. The research of Fudan Wuda alumni is interesting](/img/a8/51b95432a9c8f25d8440cfd80926ce.png)
[NLP] this year's college entrance examination English AI score is 134. The research of Fudan Wuda alumni is interesting

The boss asked me to write an app automation -- yaml file reading -- with the whole framework source code attached

第六天 脚本与动画系统

增强 Jupyter Notebook 的功能,这里有四个妙招
随机推荐
装饰模式(Decorator)
Huawei OSPF single region
Instant messaging and BS architecture simulation of TCP practical cases
Thread lifecycle
Au revoir! Navigateur ie, cette route Edge continue pour IE
栈的弹出压入序列<难度系数>
MySQL的开发环境和测试环境有什么区别??
==And eqauls()
Installing redis under Linux and windows (ultra detailed graphic tutorial)
Naming rules and specifications for identifiers
fastposter v2.8.4 发布 电商海报生成器
优秀笔记软件盘点:好看且强大的可视化笔记软件、知识图谱工具Heptabase、氢图、Walling、Reflect、InfraNodus、TiddlyWiki
第六天 脚本与动画系统
Methods for creating multithreads ---1 creating subclasses of thread class and multithreading principle
The boss asked me to write an app automation -- yaml file reading -- with the whole framework source code attached
mysql打不开,闪退
请教下, 我在本地idea运行flinkcdc的mysql到mysql全量同步,这个是在我本地ide
布隆过滤器 课程研究报告
Starting from full power to accelerate brand renewal, Chang'an electric and electrification products sound the "assembly number"
Teach you how to handle the reverse SVG mapping of JS