Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将Http请求(Feign)自动转换成客户端负载均衡的服务调用。微服务间的调用,API网关的请求转发等内容,实际上都是通过Ribbon来实现的,也就是说, Spring Cloud Ribbon是基于Ribbon实现的工具。
一、架构演进
二、使用Ribbon将user-center微服务注册到Nacos
2.1、在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2.2、在application.yml中添加属性
spring:
cloud:
nacos:
discovery:
#指定nacos server的地址,用于微服务发现
server-addr: localhost:8848
#设置机房名称(指定集群名称)
cluster-name: BeiJing
#在nacos中配置命名空间(指定namespace),并且获得uuid
#namespace: 980af6bb-ce43-43f2-91de-9878ca25fa3e
#cluster-name: NanJing
#指定实例元数据
#metadata:
# instance: I'm instance meta data
application:
name: user-center
2.3、配置权重规则
一个服务可以有多个实例,例如我们的 user-service,可以有:
- 127.0.0.1:8081
- 127.0.0.1:8082
- 127.0.0.1:8083
假如这些实例分布于全国各地的不同机房,例如:
- 127.0.0.1:8081,在杭州机房
- 127.0.0.1:8082,在杭州机房
- 127.0.0.1:8083,在上海机房
Nacos就将同一机房内的实例,划分为一个集群。
微服务互相访问时,应该尽可能访问同集群实例,因为本地访问速度更快。当本集群内不可用时,才访问其它集群。例如:杭州机房内的 order-service 应该优先访问同机房的 user-service。
将规则设置为同集群优先
package personal.qin.usercenter.configuration;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
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;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Slf4j
public class NacosSameClusterWeightedRule extends AbstractLoadBalancerRule {
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
@Override
public Server choose(Object o) {
try {
//拿到配置文件中的集群名称BeiJing
String clusterName = nacosDiscoveryProperties.getClusterName();
BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
//想要请求的微服务的名称
String name = loadBalancer.getName();
//获取服务发现的相关API
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
//1、找到指定服务的所有实例A
List<Instance> instances = namingService.selectInstances(name, true);
//2、过滤出相同集群下的所有实例B
List<Instance> sameClusterInstances = instances.stream().filter(instance -> Objects.equals(instance.getClusterName(), clusterName)).collect(Collectors.toList());
//3、如果B是空,就用A
List<Instance> instancesToBeChoosen = new ArrayList<Instance>();
if(CollectionUtils.isEmpty(sameClusterInstances)){
instancesToBeChoosen = instances;
log.warn("发生跨集群的调用,name={}, clusterName={}, instances={}", name, clusterName, instances);
} else {
instancesToBeChoosen = sameClusterInstances;
}
//4、基于权重的负载均衡算法,返回一个实例
Instance instance = ExtendBalancer.getHostByRandomWeight2(instancesToBeChoosen);
log.info("选择的实例是:port={}, instance={}", instance.getPort(), instance);
return new NacosServer(instance);
} catch (NacosException e) {
log.error("发生异常了", e);
return null;
}
}
}
class ExtendBalancer extends Balancer {
public static Instance getHostByRandomWeight2(List<Instance> hosts){
return getHostByRandomWeight(hosts);
}
}
2.4、创建Ribbon配置类
注意:该包一定不能和BootApplication同包
应用规则:同集群优先
package ribbonconfiguration;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import personal.qin.usercenter.configuration.NacosSameClusterWeightedRule;
@Configuration
public class RibbonConfiguration {
@Bean
public IRule ribbonRule(){
return new NacosSameClusterWeightedRule(); //同集群优先规则
}
}
2.5、创建Ribbon全局配置类
由于user-center为服务提供者,当前项目content-center为服务消费者,服务消费者需要通过Ribbon向Nacos服务发现组件获取可用的服务提供者(user-center),所以需要在当前项目中配置服务提供者user-center
package personal.qin.usercenter.configuration;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Configuration;
import ribbonconfiguration.RibbonConfiguration;
@Configuration
//Ribbon全局配置
@RibbonClients(defaultConfiguration = RibbonConfiguration.class)
public class UserCenterRibbonConfiguration {
}
2.6、测试效果
运行微服务,在nacos控制台可以看到user-center微服务已经被注册