自定义FeignLoadBalancer
此功能主要用于本地服务路由规则改造
需要根据实际请求觉得客户端可用节点
配置类
package com.wmang.sevice.client.seviceclient.config;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author: wmang
* @Date: 2020/12/2 00:13
* @Description:
*/
@Configuration
public class FeignAutoConfig {
@Bean
@Scope("prototype")
public IRule getRule(){
return new CustomRule();
}
}
重写选定规则
package com.wmang.sevice.client.seviceclient.config;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.omg.PortableServer.THREAD_POLICY_ID;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* @Author: wmang
* @Date: 2020/12/2 00:15
* @Description:
*/
@Slf4j
public class CustomRule extends AbstractLoadBalancerRule {
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
public Server choose(ILoadBalancer loadBalancer, Object key) {
if (null == loadBalancer) {
log.error("loadBalancer is null");
return null;
}
List<Server> upServer = loadBalancer.getReachableServers();
List<Server> allServer = loadBalancer.getAllServers();
int upServerCount = upServer.size();
int allServerCount = allServer.size();
if (upServerCount == 0 || allServerCount == 0) {
log.error("loadBalancer not has available server");
return null;
}
Server server = null;
int total = 0;
int currentIndex = 0;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
//通过负载均衡来计算获取server
if (total < 5) {
server = upServer.get(currentIndex);
total++;
} else {
total = 0;
currentIndex++;
if (currentIndex >= upServerCount) {
currentIndex = 0;
}
}
if (null == server) {
Thread.yield();
continue;
}
if (server.isAlive()) {
return server;
}
server = null;
Thread.yield();
}
//正常情况下,每次应该都能选择一个up实例
return server;
}
/**
* 获取一个随机数
*
* @param serverCount
* @return
*/
protected int chooseRandomInt(int serverCount) {
return ThreadLocalRandom.current().nextInt(serverCount);
}
}