负载均衡的原理

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 发起请求
相关推荐
cui_ruicheng7 分钟前
Linux IO入门(三):手写一个简易的 mystdio 库
linux·运维·服务器
telllong7 分钟前
MCP协议实战:30分钟给Claude接上你公司的内部API
linux·运维·服务器
正在走向自律16 分钟前
KingbaseES 基础 SQL 语法与日常运维实操手册
运维·数据库·sql·kingbasees
实心儿儿29 分钟前
Linux —— 进程概念 - 程序地址空间
linux·运维·算法
buhuizhiyuci33 分钟前
linux篇-应用商店:“yum / apt“ 的详解
linux·运维·服务器
Tisfy1 小时前
CORS 跨域重定向后 Origin 变 null —— 一次 Nginx 字体加载失败的排查记录
运维·nginx·html·cors
程序猿阿伟1 小时前
《QClaw隐藏的GitHub自动化神级用法》
运维·自动化·github
ulias2121 小时前
进程初识(1)
linux·运维·服务器·网络·c++
福大大架构师每日一题2 小时前
nginx 1.30.0稳定版深度解析:Early Hints、HTTP/2后端、MPTCP全量上线,1.29.x分支精华全面整合
运维·nginx·http
Paraverse_徐志斌2 小时前
Linux 内核与 Zero-Copy 零拷贝
linux·运维·内核·零拷贝