负载均衡的原理

SpringCloud 中负载均衡的原理

前情 : 启动了两个 UserService 客户端和一个 OrderService 客户端,且都已经注册到 Eureka 中。

服务消费者OrderService,使用注册中心的名字代替 ip 和端口,设置负载均衡策略 ,直接调用了其中

之一的服务提供者。

java 复制代码
    /**
     *  创建 RestTemplate 并注入 Spring 容器
     *  RestTemplate 是Spring Cloud框架中的一个HTTP客户端工具,
     *  用于发送HTTP请求并与远程服务进行通信。
     *  它封装了常见的HTTP操作,使得在微服务架构中进行服务间通信更加方便。
     */
    @Bean
    @LoadBalanced   
    // order-service(服务消费者) 在调用多个 user-service(服务提供者) 时,使用负载均衡算法
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
  1. 通过LoadBalancerInterceptor 负载均衡拦截器拦截到请求
java 复制代码
@Override
   public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
   		final ClientHttpRequestExecution execution) throws IOException {
   	final URI originalUri = request.getURI();
   	String serviceName = originalUri.getHost();
   	Assert.state(serviceName != null,
   			"Request URI does not contain a valid hostname: " + originalUri);
   	return this.loadBalancer.execute(serviceName,
   			this.requestFactory.createRequest(request, body, execution));
   }
  1. 通过 RibbonLoadBalancerClient 获取url 中的服务 id
java 复制代码
public <T> T execute(String serviceId, LoadBalancerRequest<T> request, Object hint)
			throws IOException {
	ILoadBalancer loadBalancer = getLoadBalancer(serviceId);
	Server server = getServer(loadBalancer, hint);
	if (server == null) {
		throw new IllegalStateException("No instances available for " + serviceId);
	}
	RibbonServer ribbonServer = new RibbonServer(serviceId, server,
			isSecure(server, serviceId),
			serverIntrospector(serviceId).getMetadata(server));
	
	return execute(serviceId, ribbonServer, request);
}
  1. 从 eureka 注册中心拉取 user-service,返回服务列表
  2. 通过 IRule 接口选择一种负载均衡策略,拉取某个服务
java 复制代码
public Server chooseServer(Object key) {
    if (this.counter == null) {
        this.counter = this.createCounter();
    }
    this.counter.increment();
    if (this.rule == null) {
        return null;
    } else {
        try {
            return this.rule.choose(key);
        } catch (Exception var3) {
            logger.warn("LoadBalancer [{}]:  Error choosing server for key {}", new Object[]{this.name, key, var3});
            return null;
        }
    }
}
  1. 修改 url 发起请求
相关推荐
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.1 小时前
Haproxy会话保持:基于Cookie优化
运维·负载均衡
学习3人组2 小时前
Docker 容器内文件↔本地双向复制备份
运维·docker·容器
crownyouyou2 小时前
Ubuntu输入法使用回车键后字符间距异常的问题
linux·运维·ubuntu
济6172 小时前
linux 系统移植(第十七期)---Linux 内核移植(5)-- 修改网络驱动(2)--- Ubuntu20.04
linux·运维·网络
街灯L3 小时前
【kylin-Linux】Flash兼容插件包安装
大数据·linux·运维·kylin
Howrun7773 小时前
Linux_C++网络编程四种CS模型
linux·运维·服务器
vortex53 小时前
如何快速删除 Linux 中的海量小文件:告别rm命令的缓慢困境
linux·运维·服务器
学习3人组5 小时前
Docker 从本地Label-studio导入 tar 镜像包
运维·docker·容器
羑悻的小杀马特5 小时前
Docker-Android 容器化 + cpolar 穿透,完善异地调试
android·运维·docker·容器·cpolar
RisunJan5 小时前
Linux命令-ldd(查看可执行程序或共享库所依赖的动态链接库)
linux·运维·服务器