首先声明Ribbon不是SpringCloud Alibaba的组件,Ribbon是Netflix的组件,但是在持续更新~
Ribbon不需要额外添加,在引用SpringCloud的时候就自动加入了
一、轮询查询
使用
在restTemplate配置类中添加注解@LoadBalanced即可
@Configuration
public class ConsumerConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
在ConsumerController类中
@GetMapping("/index")
public String index(){
return this.restTemplate.getForObject("http://provider/index",String.class);
}
会自动到nacos服务里找到provider服务,负载均衡从多个实例里调用
结果
nacos服务
调用结果:
二、随机查询
Ribbon默认是轮询查询,如果要随机负载需要在application.yml
添加配置
provider:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
三、权重查询
创建新的权重配置类NacosWeightedRule.java
package com.jili.config;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
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.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class NacosWeightedRule extends AbstractLoadBalancerRule {
//注册nacos信息
@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;
}
}
}
修改配置文件application.yml
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule ==>
NFLoadBalancerRuleClassName: com.jili.config.NacosWeightedRule(权重配置类名)
server:
port: 8180
provider:
ribbon:
NFLoadBalancerRuleClassName: com.jili.config.NacosWeightedRule
在nacos服务器上修改权重便可人为控制流量