【SpringCloud】Ribbon如何自定义客户端配置和全局配置 (3)

上面比较重要的就是在创建每个RibbonClient的ApplicationContext的createContext(name)方法,其中包含了根据哪个@Configuration配置类创建Ribbon核心接口的实现类的逻辑,故需重点分析(Ribbon核心接口讲解 参考)

那么在createContext(name)方法创建当前Ribbon Client相关的上下文,并注入配置类时,除了默认配置类RibbonClientConfiguration是写死的,其它的配置类,如default全局配置类,针对某个Ribbon Client的配置类,又是怎么配置的呢?


Spring Cloud RibbonClient的配置加载,包含全局配置及Client配置 创建RibbonClient对应ApplicationContext,并注册所有可用的Configuration配置类 //## org.springframework.cloud.context.named.NamedContextFactory#createContext() protected AnnotationConfigApplicationContext createContext(String name) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); // 1、注册专门为RibbonClient指定的configuration配置类,@RibbonClient注解 if (this.configurations.containsKey(name)) { for (Class<?> configuration : this.configurations.get(name) .getConfiguration()) { context.register(configuration); } } // 2、将为所有RibbonClient的configuration配置类注册到ApplicationContext for (Map.Entry<String, C> entry : this.configurations.entrySet()) { if (entry.getKey().startsWith("default.")) { for (Class<?> configuration : entry.getValue().getConfiguration()) { context.register(configuration); } } } // 3、注册defaultConfigType,即Spring的默认配置类 RibbonClientConfiguration context.register(PropertyPlaceholderAutoConfiguration.class, this.defaultConfigType); context.getEnvironment().getPropertySources().addFirst(new MapPropertySource( this.propertySourceName, Collections.<String, Object> singletonMap(this.propertyName, name))); if (this.parent != null) { // Uses Environment from parent as well as beans context.setParent(this.parent); } context.refresh(); // 刷新上下文 return context; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwfggd.html