当前位置:网站首页>Ribbon principle analysis namedcontextfactory
Ribbon principle analysis namedcontextfactory
2022-07-29 03:39:00 【Gusu Leng】
Tracking Ribbon In the process of source code, I saw NamedContextFactory, Do not understand the essence of its existence , It is hereby recorded that .
stay SpringCloud in , Due to the different systems between microservices , Different configurations may be required for remote calls , For example, order system A And inventory system B,ribbon request A,B The connection timeout that may be required and the number of retries are inconsistent , How to do it at this time ribbon request A,B System
When using different configurations . So this is introduced NamedContextFactory.
From the perspective of notes :
It can create a series of sub containers , Allow a series of Specification Define your own... In each sub container bean. You can see FeignClientFactory,SpringClientFactory. It's from netflix Draw lessons from .

Ribbon It uses SpringClientFactory.
In this NamedContextFactory There is also an internal interface :Specification
The annotation means : Use name,configuration Differentiated specifications .

in general :NamedContextFactory Maintain a collection of sub containers used by a client , To configure , Get... In the container bean etc. .
In fact, this content is a little similar nacos Of group,Specification Used to configure grouping , One Specification The instance is a configuration group , Press name distinguish .NamedContextFactory It maintains a series of Specification In the instance configuration.
NamedContextFactory According to these Specification Configuration creation in creates sub containers for some columns , For this sub container, also press this name grouping . This call NamedContextFactory#getInstance It's time to take name To get , It's about getting
In that container bean.
Let's take a look first NamedContextFactory Some of the attributes inside .
1:propertySourceName,propertyName Constructor passed in assignment , A configuration will be generated in each sub container propertySourceName=propertyName
2: Map<String, AnnotationConfigApplicationContext> contexts Sub containers created by each group , It's all in this map in ,key It's grouped name. Namely Specification The one in the example name.
3:Map<String, C> configurations Store a series of Specification example ,key Namely Specification Medium name.
4:ApplicationContext parent The parent container of each child container , Generally, it is currently started spring Project context .
4:defaultConfigType A configuration class used by each sub container . Default configuration class .

1: Constructors .
The first parameter : Is the default configuration class , This configuration class , It's a public , All sub containers will load it , Hereunder createContext Method .
The second parameter , The third parameter : It's also public , Add a configuration attribute in each sub container :propertySourceName=propertyName Hereunder createContext Method .

2: Set the parent container of all child containers , When creating sub containers , If it is not empty, it will put this parent Set as your own parent container . General parent It's all current spring project .

3: This is used to create a series Specification The instance is passed in , Use the inside configuration Used to create sub containers .

4: Get the grouping of all sub containers name.

5: Get a sub container , Can be rewritten .

6: Create sub containers
protected AnnotationConfigApplicationContext createContext(String name) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
if (this.configurations.containsKey(name)) {
//this.configurations.get(name) What you get is the corresponding Specification example
for (Class<?> configuration : this.configurations.get(name) .getConfiguration()) {
// Enter a name of name Configuration class of the sub container of
context.register(configuration);
}
}
for (Map.Entry<String, C> entry : this.configurations.entrySet()) {
// Self defined Specification The instance can also be named default. start , In this way, each sub container will also use injection .
if (entry.getKey().startsWith("default.")) {
for (Class<?> configuration : entry.getValue().getConfiguration()) {
context.register(configuration);
}
}
}
// The default configuration class used by the sub container .
context.register(PropertyPlaceholderAutoConfiguration.class,
this.defaultConfigType);
// Add a configuration .
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
// The child container can get the name of the parent container bean
context.setParent(this.parent);
// solve java 11 The problem of
// jdk11 issue
// https://github.com/spring-cloud/spring-cloud-netflix/issues/3101
context.setClassLoader(this.parent.getClassLoader());
}
context.setDisplayName(generateDisplayName(name));
context.refresh();
return context;
}7: according to name Get an instance , First, according to name Get a sub container and then get bean.
public <T> T getInstance(String name, Class<T> type) {
AnnotationConfigApplicationContext context = getContext(name);
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
type).length > 0) {
return context.getBean(type);
}
return null;
}practice
We customize a set Client, and Specification Feel this mechanism .
As a client
public class MytestClientNamedContextFactory extends NamedContextFactory<MytestClientSpecification> {
public MytestClientNamedContextFactory() {
super(BeanBaseConfig.class, "test", "myTest");
}
}
Specification example
public class MytestClientSpecification implements NamedContextFactory.Specification {
private String name;
private Class<?>[] configuration;
public MytestClientSpecification(){
}
public MytestClientSpecification(String name, Class<?>[] configuration){
this.name=name;
this.configuration=configuration;
}
@Override
public String getName() {
return name;
}
@Override
public Class<?>[] getConfiguration() {
return configuration;
}
}
Default configuration class
@Configuration
public class BeanBaseConfig {
@Bean
public TestBean testBeanCommon(){
TestBean testBean = new TestBean();
testBean.setBeanName("byBeanBaseConfig1");
return testBean;
}
}
@Configuration
public class BeanBaseConfig1 {
@Bean
public TestBean testBean(){
TestBean testBean = new TestBean();
testBean.setBeanName("byBeanBaseConfig1");
return testBean;
}
}
@Configuration
public class BeanBaseConfig2 {
@Bean
public TestBean testBean1(){
TestBean testBean = new TestBean();
testBean.setBeanName("byBeanBaseConfig1");
return testBean;
}
}
public class TestBean {
private String beanName="testBean";
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
}test :
@SpringBootTest
public class SpringRunTest {
@Test
public void test(){
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
parent.register(BeanBaseConfig.class);
parent.refresh();
// Declare a client Use the default configuration BeanBaseConfig
MytestClientNamedContextFactory testClient=new MytestClientNamedContextFactory();
// Declare the specification Actually this specification Equivalent to one nacos group Group the configurations
// For example ribbon client in It may be necessary to request that the configuration of the order microservice and the inventory microservice are different You need it
MytestClientSpecification mytestClientSpecification1 = new MytestClientSpecification("specification1",new Class[]{BeanBaseConfig1.class});
MytestClientSpecification mytestClientSpecification2 = new MytestClientSpecification("specification2",new Class[]{BeanBaseConfig1.class, BeanBaseConfig2.class});
testClient.setConfigurations(Arrays.asList(mytestClientSpecification1,mytestClientSpecification2));
testClient.setApplicationContext(parent);
System.out.println(testClient.getInstances("specification1", TestBean.class));
System.out.println("=====================================");
System.out.println(testClient.getInstances("specification2", TestBean.class));
}
}give the result as follows :
{[email protected], [email protected]}
=====================================
{[email protected], [email protected], [email protected]}You can see through Specification Instances can separate sub containers .
Ribbon Also use this mechanism . Back analysis Ribbon I'll mention it when I get the source code .
边栏推荐
- Build redis environment under windows and Linux
- i. MX 8m plus integrated dedicated neural processing engine (NPU)
- ROS-Errror:Did you forget to specify generate_ messages(DEPENDENCIES ...)?
- Rdkit I: using rdkit to screen the structural characteristics of chemical small molecules
- Simple code implementation of decision tree
- Deep into C language (1) -- operators and expressions
- (nowcoder22529C)dinner(容斥原理+排列组合)
- Inclusion exclusion principle
- RTP send and receive h265
- Pp-yoloe details
猜你喜欢

深入C语言(3)—— C的输入输出流

Rdkit II: use rdkit screening to screen 2D pharmacophores of chemical small molecules

容斥原理
![MOS管 —— 快速复苏应用笔记(贰)[参数与应用]](/img/54/eb040a51304192def8cfb360c7c213.png)
MOS管 —— 快速复苏应用笔记(贰)[参数与应用]

04 | background login: login method based on account and password (Part 1)

Inclusion exclusion principle

Excel splicing database statement

Instance setup flask service (simple version)

for_ Example of each usage

Understanding of p-type problems, NP problems, NPC problems, and NP hard problems in natural computing
随机推荐
(newcoder 15079)无关(容斥原理)
Machine learning based on deepchem
NXP i.mx8mp-deepviewrt
Sleuth+zipkin to track distributed service links
Excel拼接数据库语句
Precautions for using latex
The latest second edition of comic novels, listening to books, three in one, complete source code / integrated visa free interface / building tutorials / with acquisition interface
再学EXKMP(EXKMP模板)
How close can QA be to business code Direct exposure of defects through codediff
How does DataGrid export and recover the entire database data, using a single SQL file
Sunflower senior product director technology sharing: "how to apply national remote control" in AD domain environment
Makefile details
深入C语言(3)—— C的输入输出流
1.4 nn. Module neural network (II)
Excel splicing database statement
Complexity analysis learning
Easy to use remote sensing data set download website~~~
Swing V2: towards a larger model with larger capacity and higher resolution
Example analysis of while, repeat and loop loops in MySQL process control
2 neural network toolbox NN