负载均衡的原理

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 发起请求
相关推荐
网络安全(华哥)1 小时前
网络安全服务实施流程管理 网络安全服务体系
运维·服务器·网络
致奋斗的我们1 小时前
Nginx反向代理及负载均衡
linux·运维·mysql·nginx·负载均衡·shell·openeluer
Ares-Wang1 小时前
负载均衡 方式
运维·负载均衡
钗头风1 小时前
3.Docker常用命令
运维·docker·容器
朝九晚五ฺ2 小时前
【Linux探索学习】第三十弹——线程互斥与同步(上):深入理解线程保证安全的机制
linux·运维·学习
不要吃栗子李2 小时前
高级运维:1. 对比 LVS 负载均衡群集的 NAT 模式和 DR 模式,比较其各自的优势 。2. 基于 openEuler 构建 LVS-DR 群集。
运维·负载均衡·lvs
ITPUB-微风3 小时前
网易严选DevOps实践:从传统到云原生的演进
运维·云原生·devops
圣心4 小时前
Ollama Docker 镜像部署
运维·docker·容器
Karoku0664 小时前
【CI/CD】Jenkinsfile管理+参数化构建+邮件通知以及Jenkins + SonarQube 代码审查
运维·ci/cd·容器·kubernetes·jenkins·rancher
Lxyand15 小时前
网工项目实践2.4 北京公司安全加固、服务需求分析及方案制定
运维·服务器·网络·安全·智能路由器