本文主要是介绍Ribbon负载均衡(Load Balance),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
LB负载均衡(Load Balance):将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)
Nginx服务端负载均衡和Ribbon本地负载均衡的区别:
Nginx是服务器负载均衡,客户端所有的请求都会交给nginx,然后由nginx实现转发请求。即负载均衡是由服务端实现的。
Ribbon是本地负载均衡,在调用微服务接口的时候,会在注册中心上获取注册信息服务列表之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术。
Ribbon的使用
@Configuration
public class ApplicationContextConfig
{@Bean@LoadBalanced //实现轮询方式的负载均衡public RestTemplate getRestTemplate(){return new RestTemplate();}
}
自定义类实现轮询方式的负载均衡:
目录结构
LoadBalancer.java
import org.springframework.cloud.client.ServiceInstance;import java.util.List;public interface LoadBalancer
{ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
MyLB.java
package com.atguigu.springcloud.lb;import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;@Component
public class MyLB implements LoadBalancer {private AtomicInteger atomicInteger = new AtomicInteger(0);public final int getAndIncrement(){int current;int next;do {current = this.atomicInteger.get();next = current >= 2147483647 ? 0 : current + 1;}while(!this.atomicInteger.compareAndSet(current,next));System.out.println("*****第几次访问,次数next: "+next);return next;}//负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标 ,每次服务重启动后rest接口计数从1开始。@Overridepublic ServiceInstance instances(List<ServiceInstance> serviceInstances){int index = getAndIncrement() % serviceInstances.size();return serviceInstances.get(index);}
}
调用:OrderController.java
@Resourceprivate RestTemplate restTemplate;@Resourceprivate LoadBalancer loadBalancer;@Resourceprivate DiscoveryClient discoveryClient;@GetMapping(value = "/consumer/payment/lb")public String getPaymentLB(){List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");if(instances == null || instances.size() <= 0){return null;}ServiceInstance serviceInstance = loadBalancer.instances(instances);URI uri = serviceInstance.getUri();return restTemplate.getForObject(uri+"/payment/lb",String.class);}
这篇关于Ribbon负载均衡(Load Balance)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!