1、spring cloud 2020.0.1 LoadBalancer负载均衡算法切换
springcloud 2020.0.1 版本之后 删除了eureka中的ribbon,替代ribbon的是spring cloud自带的LoadBalancer,默认使用的是轮询的方式
如果切换,需要我们进行配置
我们这里使用的是restTemplate作为访问工具
1.1 首先定义一个CustomLoadBalancerConfiguration.class 这个包可以在主启动类所在包及其子包下 这一点和ribbon不同
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
//这里 不需要 @configuration注解 不需要
public class CustomLoadBalancerConfiguration {
@Bean
ReactorLoadBalancer randomLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RandomLoadBalancer(loadBalancerClientFactory
.getLazyProvider(name, ServiceInstanceListSupplier.class),
name);
}
}
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
//在这里配置我们自定义的LoadBalancer策略 如果有大佬想自己扩展算法 需要实现ReactorServiceInstanceLoadBalancer接口
//@LoadBalancerClients(defaultConfiguration = {name = "CLOUD-PAYMENT-SERVICE", configuration = CustomLoadBalancerConfiguration.class})
//注意这里的name属性 需要和eureka页面中的服务提供者名字一直 此时页面中是大写
@LoadBalancerClient(name = "CLOUD-PAYMENT-SERVICE",configuration = CustomLoadBalancerConfiguration.class)
public class ApplicationContextConfig {
//将这个对象放入ioc容器
@Bean
@LoadBalanced //使用这个注解给restTemplate赋予了负载均衡的能力
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
注意@LoadBalancerClients 或者@LoadBalancerClient注解中的name或者value属性一定要和服务中心中注册的服务名一致 大小写一定要一致
我的做法很简单 看源码的RoundRobinLoadBalancer的实现 copy一下在最后选择的时候改变一下策略即可 看下面代码中的注释
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.*;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
//这个方法基本是copy的RoundRobinLoadBalancer自己改一改出来的
public class PeachLoadBalancer implements ReactorServiceInstanceLoadBalancer {
private static final Log log = LogFactory.getLog(RoundRobinLoadBalancer.class);
final AtomicInteger position;//请求的次数
final String serviceId; //服务名称 用于提示报错信息的
private int flag = 0; //自己定义的计数器
//两个参数的构造方法 需要服务名称和实例提供者 这个在方法中传递进来
public PeachLoadBalancer(ObjectProvider serviceInstanceListSupplierProvider,
String serviceId) {
//如果不传人请求次数就自己初始化 反正每次都+1
this(new Random().nextInt(1000), serviceId,serviceInstanceListSupplierProvider);
}
public PeachLoadBalancer(int seedPosition, String serviceId, ObjectProvider serviceInstanceListSupplierProvider) {
this.position = new AtomicInteger(seedPosition);
this.serviceId = serviceId;
this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
}
ObjectProvider serviceInstanceListSupplierProvider;
@Override
public Mono> choose(Request request) {
//从服务提供者中获取到当前request请求中的serviceInstances并且遍历
ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider
.getIfAvailable(NoopServiceInstanceListSupplier::new);
return supplier.get(request).next()
.map(serviceInstances -> processInstanceResponse(supplier, serviceInstances));
}
private Response processInstanceResponse(ServiceInstanceListSupplier supplier,
List serviceInstances) {
Response serviceInstanceResponse = getInstanceResponse(serviceInstances);
if (supplier instanceof SelectedInstanceCallback && serviceInstanceResponse.hasServer()) {
((SelectedInstanceCallback) supplier).selectedServiceInstance(serviceInstanceResponse.getServer());
}
return serviceInstanceResponse;
}
private Response getInstanceResponse(List instances) {
if (instances.isEmpty()) {
if (log.isWarnEnabled()) {
log.warn("No servers available for service: " + serviceId);
}
return new EmptyResponse();
}
//pos是当前请求的次数 这样可以自定义负载均衡的切换 这个每次+1的操作是复制的 最好是不删
int pos = Math.abs(this.position.incrementAndGet());
if (pos%4==0){
//是4的倍数就切换
flag += 1;
}
if (flag >= instances.size()){
flag = 0;
}
//主要的就是这句代码设置负载均衡切换
ServiceInstance instance = instances.get(flag);
return new DefaultResponse(instance);
}
}
之后在配置的地方也就是CustomLoadBalancerConfiguration配置类中返回我们自己的方案即可
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
public class CustomLoadBalancerConfiguration {
@Bean
ReactorLoadBalancer randomLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
// 这里返回了新的randomLoadBalancer
//这里返回了我自己定义的方法
return new PeachLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
// return new RandomLoadBalancer(loadBalancerClientFactory
// .getLazyProvider(name, ServiceInstanceListSupplier.class),
// name);
}
}