Nacos中默认继承Ribbon
在上一篇文章基础上,Consumer模块配置类新增@LoadBalanced注解
@Configuration
public class ConsumerConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
ConsumerController改造
@RestController
public class ConsumerController {
private final DiscoveryClient discoveryClient;
private final RestTemplate restTemplate;
//访问服务提供者服务的前缀,http://服务名
private static final String REST_URL_PREFIX = "http://provider";
@Autowired
public ConsumerController(DiscoveryClient discoveryClient, RestTemplate restTemplate) {
this.discoveryClient = discoveryClient;
this.restTemplate = restTemplate;
}
@GetMapping("/instances")
public List<ServiceInstance> getInstances() {
return discoveryClient.getInstances("provider");
}
@GetMapping("/index")
public String index() {
return "consumer远程调用provier:" + this.restTemplate.getForObject(REST_URL_PREFIX + "/index", String.class);
}
}
默认采用轮询算法,常用的还有随机和权重算法
随机
server:
port: 9090
# 负载均衡策略 服务名+ribbon+策略(不配置默认使用轮询策略)
provider:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
Nacos 权重
public class NacosWeightedRule extends AbstractLoadBalancerRule {
private static final Logger log = LoggerFactory.getLogger(NacosWeightedRule.class);
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
//读取配置文件
}
@Override
public Server choose(Object o) {
ILoadBalancer loadBalancer = this.getLoadBalancer();
BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) loadBalancer;
//获取要请求的微服务名称
String name = baseLoadBalancer.getName();
//获取服务发现的相关API
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
try {
Instance instance = namingService.selectOneHealthyInstance(name);
log.info("选择的实例是port={},instance={}", instance.getPort(), instance);
return new NacosServer(instance);
} catch (NacosException e) {
e.printStackTrace();
return null;
}
}
}
server:
port: 9090
# 负载均衡策略 服务名+ribbon+策略(不配置默认使用轮询策略)
provider:
ribbon:
NFLoadBalancerRuleClassName: com.godfrey.config.NacosWeightedRule
默认权重都是1,修改权重再进行测试