Spring Cloud NamedContextFactory 原理分析

本文深入探讨了Spring Cloud的NamedContextFactory,它用于根据服务名称创建独立的ApplicationContext,实现不同服务调用的负载均衡配置隔离。通过NamedContextFactory,我们可以针对不同服务定制负载策略,如数据服务和用户中心服务。文中详细分析了NamedContextFactory的作用、构造方法及其实现原理,指出其如何利用Map存储子容器及其对应的ApplicationContext,以及在负载均衡场景中的应用,如设置特定服务的超时时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

系列文章:
Spring Cloud LoadBalancer之负载均衡简介
Spring Cloud NamedContextFactory 原理分析
Ribbon 的替代品 Spring Cloud Loadbalancer 使用与原理分析

测试代码地址

1.1 NamedContextFactory 作用

ribbon 与 loadbalancer 都能做到对不同的调用服务使用不同的负载均衡配置。

例如:数据服务需要查询的时间较长,用户中心服务查询用户信息的时间较短,二者可以采用不同的负载策略。

要实现上述要求,可以使用 Spring Cloud 提供的 NamedContextFactory 实现;他的作用就是根据名称去存储不同的 ApplicationContext,这样就能实现不同的名称的 Bean 隔离了。

由于NamedContextFactory 类有一个字段(parent)保存了最外层的 Bean 上下文,因此可以获取到父级传过来的上下文内容。
image-20220420183018646

以下图为例,在同一个 NamedContextFactory 中,parent有一个 paren bean,两个 children都有各自的 child bean,children 上下文是能够访问到父上下文的,并且访问到的父 bean 都是同一个类实例。
image-20220421095558073

以下代码是校验从父容器获取到的 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 =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值