当前位置:网站首页>Ribbon源码分析之@LoadBalanced与LoadBalancerClient
Ribbon源码分析之@LoadBalanced与LoadBalancerClient
2022-06-24 18:58:00 【华为云】
Ribbon源码分析之@LoadBalanced与LoadBalancerClient
@LoadBalanced注解
@LoadBalanced注解用来给RestTemplate做标记,方便使用负载均衡的客户端LoadBalancerClient来配置它。
LoadBalancerClient:
public interface LoadBalancerClient { /** * Choose a ServiceInstance from the LoadBalancer for the specified service * @param serviceId the service id to look up the LoadBalancer * @return a ServiceInstance that matches the serviceId */ ServiceInstance choose(String serviceId); /** * execute request using a ServiceInstance from the LoadBalancer for the specified * service * @param serviceId the service id to look up the LoadBalancer * @param request allows implementations to execute pre and post actions such as * incrementing metrics * @return the result of the LoadBalancerRequest callback on the selected * ServiceInstance */ <T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException; /** * Create a proper URI with a real host and port for systems to utilize. * Some systems use a URI with the logical serivce name as the host, * such as http://myservice/path/to/service. This will replace the * service name with the host:port from the ServiceInstance. * @param instance * @param original a URI with the host as a logical service name * @return a reconstructed URI */ URI reconstructURI(ServiceInstance instance, URI original);}接口中,我们通过定义抽象方法来了解客户端负载均衡器中应具备的能力
ServiceInstance choose(String serviceId); 根据传入的服务名serviceId从负载均衡器中挑选一个对应服务的实例
T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException; 从负载均衡器中挑选出的服务实例来执行请求内容
URI reconstructURI(ServiceInstance instance, URI original); 为系统构建一个合适的host:port 形式的URI
在分布式系统中,我们使用逻辑上的服务名称作为host来构建URI进行请求。在操作定义中,ServiceInstance对象带有host和port具体服务实例,后者URI对象使用逻辑服务名定义为host的URI,返回的URI内容是通过ServiceInstance 的服务实例详情拼接出来的host:port形式的请求地址。
小知识,大挑战!本文正在参与「程序员必备小知识」创作活动
LoadBalancerClient
LoadBalancerAutoConfiguration实现客户端负载均衡器的自动化配置类。
LoadBalancerAutoConfiguration:
import java.util.ArrayList;import java.util.Collections;import java.util.List;import org.springframework.beans.factory.SmartInitializingSingleton;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.ClientHttpRequestInterceptor;import org.springframework.web.client.RestTemplate;/** * Auto configuration for Ribbon (client side load balancing). * * @author Spencer Gibb * @author Dave Syer */@Configuration@ConditionalOnClass(RestTemplate.class)@ConditionalOnBean(LoadBalancerClient.class)public class LoadBalancerAutoConfiguration { @LoadBalanced @Autowired(required = false) private List<RestTemplate> restTemplates = Collections.emptyList(); @Bean public SmartInitializingSingleton loadBalancedRestTemplateInitializer( final List<RestTemplateCustomizer> customizers) { return new SmartInitializingSingleton() { @Override public void afterSingletonsInstantiated() { for (RestTemplate restTemplate : LoadBalancerAutoConfiguration.this.restTemplates) { for (RestTemplateCustomizer customizer : customizers) { customizer.customize(restTemplate); } } } }; } @Bean @ConditionalOnMissingBean public RestTemplateCustomizer restTemplateCustomizer( final LoadBalancerInterceptor loadBalancerInterceptor) { return new RestTemplateCustomizer() { @Override public void customize(RestTemplate restTemplate) { List<ClientHttpRequestInterceptor> list = new ArrayList<>( restTemplate.getInterceptors()); list.add(loadBalancerInterceptor); restTemplate.setInterceptors(list); } }; } @Bean public LoadBalancerInterceptor ribbonInterceptor( LoadBalancerClient loadBalancerClient) { return new LoadBalancerInterceptor(loadBalancerClient); }}LoadBalancerAutoConfiguration类头的注解表示Ribbon实现的负载均衡自动化配置需要满足两个条件
- @ConditionalOnClass(RestTemplate.class):RestTemplate必须在当前工程的环境中
- @ConditionalOnBean(LoadBalancerClient.class):在Spring的Bean工厂中必须有LoadBalancerClient的实现Bean
自动化配置类中主要做三件事:
- 创建一个LoadBalancerInterceptor的Bean,用于实现对客户端发起请求时进行拦截,实现客户端负载均衡
- 创建RestTemplateCustomizer的Bean,用于RestTemplate增加LoadBalancerInterceptor拦截器
- 维护被LoadBalanced注解修饰的RestTemplate对象列表,并在这里进行初始化,通过RestTemplateCustomizer的实例给客户端负载均衡的RestTemplate增加LoadBalancerInterceptor拦截器
总结
这就是LoadBalancerAutoConfiguration的源码分析,它可以实现客户端负载均衡器的自动化配置类。这下一篇文章中我们要分析拦截器LoadBalancerInterceptor做了什么功能,我们下一篇文章不见不散咯。让我们一起深入Ribbon源码,共同学习
边栏推荐
- [go language questions] go from 0 to entry 4: advanced usage of slice, elementary review and introduction to map
- Bytebase 加入阿裏雲 PolarDB 開源數據庫社區
- Real time rendering: the difference between real-time, offline, cloud rendering and hybrid rendering
- Camera module and hardware interface of Camera1 camera
- Example analysis of corrplot related heat map beautification in R language
- NFT pledge liquidity mining system development technology
- Will the CDC read out of order when I use SQL
- Clustered index (clustered index), nonclustered index (nonclustered index)
- 60 divine vs Code plug-ins!!
- 应用实践 | 海量数据,秒级分析!Flink+Doris 构建实时数仓方案
猜你喜欢

Network security review office starts network security review on HowNet

The agile way? Is agile development really out of date?

Using dynamic time warping (DTW) to solve the similarity measurement of time series and the similarity identification analysis of pollution concentration in upstream and downstream rivers

Starring develops httpjson access point + Database

Confirm whether the host is a large terminal or a small terminal

Camera module and hardware interface of Camera1 camera

Where are Xiaomi mobile phone's favorite SMS and how to delete them

Five day summary of software testing

Working for 6 years with a monthly salary of 3W and a history of striving for one PM

Example analysis of corrplot related heat map beautification in R language
随机推荐
starring开发HttpJson接入点+数据库
SQL export CSV data, unlimited number of entries
全链路业务追踪落地实践方案
What type of datetime in the CDC SQL table should be replaced
请教一个问题。adbhi支持保留一个ID最新100条数据库,类似这样的操作吗
R language 4.1.0 software installation package and installation tutorial
Apache+php+mysql environment construction is super detailed!!!
Mq-2 smoke concentration sensor (STM32F103)
Five day summary of software testing
Experience of MDM master data project implementation for manufacturing projects
技术实现 | Apache Doris 冷热数据存储(一)
Vs2017 add header file path method
Maps are grouped according to the values of the passed in parameters (similar to database groupby)
SaltStack State状态文件配置实例
Based on STM32F103 0.96 inch OLED LCD driver (IIC communication)
JMeter environment deployment
Methods for comparing float types in the kernel
Where are Xiaomi mobile phone's favorite SMS and how to delete them
PingCAP 入选 2022 Gartner 云数据库“客户之声”,获评“卓越表现者”最高分
Some small requirements for SQL Engine for domestic database manufacturers