扩展ribbon-支持nacos权重负载均衡

设置权重

扩展ribbon-支持nacos权重负载均衡_第1张图片

java配置

package com.java.sa.content.config;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;

/**
 * @author jiangli
 * @since 2020/2/9 11:30
 * 扩展ribbon-支持nacos权重负载均衡
 */
@Slf4j
public class NacosWeightedRule extends AbstractLoadBalancerRule {
	@Autowired
	private NacosDiscoveryProperties discoveryProperties;

	@Override
	public Server choose(Object key) {
		BaseLoadBalancer loadBalancer = (BaseLoadBalancer) getLoadBalancer();
		String name = loadBalancer.getName();
		try {
			Instance instance = discoveryProperties.namingServiceInstance().selectOneHealthyInstance(name);

			// log.info("选中的instance = {}", instance);

			// instance转server
			return new NacosServer(instance);
		} catch (NacosException e) {
			log.error("发生异常", e);
			return null;
		}
	}

	@Override
	public void initWithNiwsConfig(IClientConfig iClientConfig) {
	}
}
package com.java.sa.content.config;

import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author jiangli
 * @since 2020/2/9 12:16
 */
@Configuration
public class RibbonConfig {

	@Bean
	public IRule ribbonRule() {
		return new NacosWeightedRule();
	}
}

 Hoxton就会有替代的实现

 

你可能感兴趣的:(扩展ribbon-支持nacos权重负载均衡)