Ribbon自定义算法

Ribbon自定义算法实现:

主启动类配置开启自定义算法:

添加 @RibbonClient(name = "MICROSERVICECLOUD-DEPT",configuration=MySelfRule.class)   配置

name:指定对使用算法的服务名称

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "MICROSERVICECLOUD-DEPT",configuration=MySelfRule.class)
public class DeptConsumer80_App {

	public static void main(String[] args) {
		SpringApplication.run(DeptConsumer80_App.class, args);

	}

}

自定义算法类:

@Configuration
public class MySelfRule {

	@Bean
	public IRule muRule() {
		// return new RandomRule();// 随机
		return new RandomRule_ZY();
	}
}

下面实现自定义算法类 首先继承 AbstractLoadBalancerRule 接口:

自定义算法设定轮询服务器,每个服务器访问五次

下面完整代码:

public class RandomRule_ZY extends AbstractLoadBalancerRule {

	private int total = 0; // 总共被调用的次数,目前要求每台被调用5次
	private int currentIndex = 0; // 当前提供服务的机器号

	public Server choose(ILoadBalancer lb, Object key) {
		if (lb == null) {
			return null;
		}
		Server server = null;

		while (server == null) {
			if (Thread.interrupted()) {
				return null;
			}
			List upList = lb.getReachableServers();
			List allList = lb.getAllServers();

			int serverCount = allList.size();
			if (serverCount == 0) {
				return null;
			}

			if (total < 5) {
				server = upList.get(currentIndex);
				total++;
			} else {
				total = 0;
				currentIndex++;
				if (currentIndex >= upList.size()) {
					currentIndex = 0;
				}
			}

			if (server == null) {
				Thread.yield();
				continue;
			}

			if (server.isAlive()) {
				return (server);
			}

			server = null;
			Thread.yield();
		}

		return server;

	}

	@Override
	public Server choose(Object key) {
		return choose(getLoadBalancer(), key);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig arg0) {
	}

}

 

你可能感兴趣的:(springCloud,Spring-boot)