系列文章:
Spring Cloud LoadBalancer之负载均衡简介
Spring Cloud NamedContextFactory 原理分析
Ribbon 的替代品 Spring Cloud Loadbalancer 使用与原理分析
1.1 NamedContextFactory 作用
ribbon 与 loadbalancer 都能做到对不同的调用服务使用不同的负载均衡配置。
例如:数据服务需要查询的时间较长,用户中心服务查询用户信息的时间较短,二者可以采用不同的负载策略。
要实现上述要求,可以使用 Spring Cloud 提供的 NamedContextFactory 实现;他的作用就是根据名称去存储不同的 ApplicationContext,这样就能实现不同的名称的 Bean 隔离了。
由于NamedContextFactory 类有一个字段(parent)保存了最外层的 Bean 上下文,因此可以获取到父级传过来的上下文内容。
以下图为例,在同一个 NamedContextFactory 中,parent有一个 paren bean,两个 children都有各自的 child bean,children 上下文是能够访问到父上下文的,并且访问到的父 bean 都是同一个类实例。
以下代码是校验从父容器获取到的 parentBean 是否为同一个,这个测试用例是能通过的:
@Test
public void context() {
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
parent.register(ParentConfig.class);
parent.refresh();
CustomNamedContextFactoryClient client = new CustomNamedContextFactoryClient(DefaultConfig.class);
// 子容器配置
CustomSpecification huaweiSpecification = new CustomSpecification("huawei", new Class[]{
HuaweiConfig.class});
CustomSpecification appleSpecification = new CustomSpecification("apple", new Class[]{
AppleConfig.class});
// 添加子容器到父容器中
client.setApplicationContext(parent);
client.setConfigurations(List.of(huaweiSpecification, appleSpecification));
// 父容器的 bean
ParentBean parentBean =