Dubbo implementation principle and source code analysis — Fine collection Netty implementation principle and source code analysis — boutique collection
“Spring Implementation principles and source code analysis — Boutique Collection” MyBatis implementation principle and source code analysis — boutique collection
Spring MVC Implementation Principle and source code Analysis — A collection of fine works Database Entity Design Collection
Spring Boot Implementation principle and source code analysis — Boutique Collection Java Interview Questions + Java Learning Guide

Abstract: the original source www.iocoder.cn/Eureka/eure… “Taro source” welcome to reprint, keep the summary, thank you!

This article is mainly based on Eureka version 1.8.X

  • 1. An overview of the
  • 2. EurekaBootStrap
    • 2.1 Initializing the Eureka-Server Configuration Environment
    • 2.2 Initializing the Eureka-Server Context
  • 3. Filter
    • 3.1 StatusFilter
    • 3.2 ServerRequestAuthFilter
    • 3.3 RateLimitingFilter
    • 3.4 GzipEncodingEnforcingFilter
    • 3.5 ServletContainer
  • 666. The eggs

🙂🙂🙂 follow wechat public number:

  1. RocketMQ/MyCAT/Sharding-JDBC all source code analysis article list
  2. RocketMQ/MyCAT/Sharding-JDBC 中文 解 决 source GitHub address
  3. Any questions you may have about the source code will be answered carefully. Even do not know how to read the source can also ask oh.
  4. New source code parsing articles are notified in real time. It’s updated about once a week.
  5. Serious source communication wechat group.

1. An overview of the

This article is based on “Eureka source code parsing — EurekaServer startup (1) EurekaServer VerConfig”, mainly share the second part of EurekaServer startup process — EurekaBootStrap.

Considering the amount of code involved in the entire initialization process, this article is divided into two parts:

Recommended Spring Cloud books:

  • Please support the legal version. Download piracy, is equal to the initiative to write low-level bugs.
  • DD — Spring Cloud Micro Services
  • Zhou Li — “Spring Cloud and Docker Micro-service Architecture Combat”
  • Buy two books together, jingdong free delivery.

2. EurekaBootStrap

Com.net flix. Eureka. EurekaBootStrap, eureka – Server startup entries.

EurekaBootStrap implements javax.mail. Servlet. ServletContextListener interface, in the servlet container (such as Tomcat, Jetty) starts, Call the #contextInitialized() method to initialize eureka-server with the following code:

Public class EurekaBootStrap implements ServletContextListener {public class EurekaBootStrap implements ServletContextListener ContextInitialized (ServletContextEvent Event) {try {// Initialize the Eureka-server configuration environment initEurekaEnvironment(); // Initialize the Eureka-server context initEurekaServerContext(); ServletContext sc = event.getServletContext(); sc.setAttribute(EurekaServerContext.class.getName(), serverContext); } catch (Throwable e) { logger.error("Cannot bootstrap eureka server :", e); throw new RuntimeException("Cannot bootstrap eureka server :", e); }}}Copy the code
  • call#initEurekaEnvironment()Method to initialize eureka-serverconfigurationThe environment.
  • call#initEurekaServerContext()Method to initialize the Eureka-server context.

2.1 Initializing the Eureka-Server Configuration Environment

// eurekabootstrap. Java /** * private static final String TEST = "TEST "; private static final String ARCHAIUS_DEPLOYMENT_ENVIRONMENT = "archaius.deployment.environment"; private static final String EUREKA_ENVIRONMENT = "eureka.environment"; Private static Final String CLOUD = "CLOUD "; private static final String CLOUD =" CLOUD "; /** * Deploy data center - DEFAULT */ private static final String DEFAULT = "DEFAULT "; private static final String ARCHAIUS_DEPLOYMENT_DATACENTER = "archaius.deployment.datacenter"; private static final String EUREKA_DATACENTER = "eureka.datacenter"; protected void initEurekaEnvironment() throws Exception { logger.info("Setting the eureka configuration.." ); / / set the configuration file data center String dataCenter. = ConfigurationManager getConfigInstance () get String (EUREKA_DATACENTER); if (dataCenter == null) { logger.info("Eureka data center value eureka.datacenter is not set, defaulting to default"); ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, DEFAULT); } else { ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_DATACENTER, dataCenter); } / / set the configuration file environment String environment. = ConfigurationManager getConfigInstance () get String (EUREKA_ENVIRONMENT); if (environment == null) { ConfigurationManager.getConfigInstance().setProperty(ARCHAIUS_DEPLOYMENT_ENVIRONMENT, TEST); logger.info("Eureka environment value eureka.environment is not set, defaulting to test"); }}Copy the code
  • Set up based onNetflix ArchaiusImplementation of the configuration file context, thus readappropriateConfiguration file. Most of the time, you just need to set it upEUREKA_ENVIRONMENTDifferent server environments (for example,PROD / TESTEtc.) read different configuration files. Implementation principle, in”Eureka source code analysis — Eureka Client initialization (a) EurekaInstanceConfig”Have detailed analysis.
  • Those interested can also read: Netflix Archaius Official Documentation — Deployment Context.

2.2 Initializing the Eureka-Server Context

The #initEurekaServerContext() method of EurekaBootStrap contains a lot of code.

2.2.1 Creating the Eureka-Server Configuration

EurekaServerConfig eurekaServerConfig = new DefaultEurekaServerConfig();
Copy the code
  • In the Eureka source code parsing – Eureka – Server startup ServerConfig of (a) “” 2.3 DefaultEurekaServerConfig” has a detailed analysis.

2.2.2 Data compatibility between eureka-Server request and response

// For backward compatibility
JsonXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(), XStream.PRIORITY_VERY_HIGH);
XmlXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(), XStream.PRIORITY_VERY_HIGH);
Copy the code
  • At present, Eureka-Server provides V2 version API, and the above code is mainly compatible with V1 version API. You can skip it.

2.2.3 Creating the Eureka-Server request and response codec

logger.info("Initializing the eureka client..." ); logger.info(eurekaServerConfig.getJsonCodecName()); ServerCodecs serverCodecs = new DefaultServerCodecs(eurekaServerConfig);Copy the code

2.2.4 create Eureka – Client

ApplicationInfoManager applicationInfoManager; if (eurekaClient == null) { EurekaInstanceConfig instanceConfig = isCloud(ConfigurationManager.getDeploymentContext()) ?  new CloudInstanceConfig() : new MyDataCenterInstanceConfig(); applicationInfoManager = new ApplicationInfoManager( instanceConfig, new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get()); EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(); eurekaClient = new DiscoveryClient(applicationInfoManager, eurekaClientConfig); } else { applicationInfoManager = eurekaClient.getApplicationInfoManager(); }Copy the code
  • Eureka-server is embedded with Eureka-client, which is used to communicate with other nodes in the Eureka-Server cluster.
  • Eureka-client initialization process, Eureka source code parsing — EurekaClient (3) EurekaClient “DiscoveryClient” is explained in detail.
  • Eureka-client can also be passed through the EurekaBootStrap constructor.

    public class EurekaBootStrap implements ServletContextListener { private EurekaClient eurekaClient; public EurekaBootStrap(EurekaClient eurekaClient) { this.eurekaClient = eurekaClient; }}Copy the code
    • Not in most cases.

2.2.5 Creating a Registry for Application Instance Information

PeerAwareInstanceRegistry registry; If (isAws (applicationInfoManager getInfo ())) {/ / AWS, Skip the registry = new AwsInstanceRegistry (eurekaServerConfig, eurekaClient getEurekaClientConfig (), serverCodecs, eurekaClient ); awsBinder = new AwsBinderDelegate(eurekaServerConfig, eurekaClient.getEurekaClientConfig(), registry, applicationInfoManager); awsBinder.start(); } else { registry = new PeerAwareInstanceRegistryImpl( eurekaServerConfig, eurekaClient.getEurekaClientConfig(), serverCodecs, eurekaClient ); }Copy the code
  • The registry class diagram for application instance information is as follows:

  • Eureka source Code Parsing — InstanceRegistry Class Relationships

2.2.6 Creating a Node set in the Eureka-Server Cluster

PeerEurekaNodes peerEurekaNodes = getPeerEurekaNodes(
      registry,
      eurekaServerConfig,
      eurekaClient.getEurekaClientConfig(),
      serverCodecs,
      applicationInfoManager
);
Copy the code

2.2.7 Creating a Eureka-Server Context

serverContext = new DefaultEurekaServerContext(
      eurekaServerConfig,
      serverCodecs,
      registry,
      peerEurekaNodes,
      applicationInfoManager
);
Copy the code
  • com.netflix.eureka.EurekaServerContext, eureka-server contextinterface, which provides the internal component object of eureka-ServerInitialize the,Shut down,To obtainMethods.
  • Com.net flix. Eureka. EurekaServerContext DefaultEurekaServerContext, eureka – Server context implementation class, the implementation code is as follows:

    Public class DefaultEurekaServerContext implements EurekaServerContext {/ * * * * / private final Eureka - Server configuration EurekaServerConfig serverConfig; /** * Eureka-server request and response codec */ private final ServerCodecs ServerCodecs; / * * * application instance information registry * / private final PeerAwareInstanceRegistry registry; /** * Private final PeerEurekaNodes PeerEurekaNodes; /** * Private Final ApplicationInfoManager ApplicationInfoManager; / /... Omit method}Copy the code

2.2.8 initialization EurekaServerContextHolder

EurekaServerContextHolder.initialize(serverContext);
Copy the code
  • Com.net flix. Eureka. EurekaServerContextHolder, eureka holders – Server context. Through it, you can easily obtain the Eureka-server context, the implementation code is as follows:

    Public class EurekaServerContextHolder {holders / * * * * / private static EurekaServerContextHolder holder; /** * Eureka-server context */ private final EurekaServerContext serverContext; private EurekaServerContextHolder(EurekaServerContext serverContext) { this.serverContext = serverContext; } public EurekaServerContext getServerContext() { return this.serverContext; Public static synchronized void initialize(EurekaServerContext)  serverContext) { holder = new EurekaServerContextHolder(serverContext); } public static EurekaServerContextHolder getInstance() { return holder; }}Copy the code

2.2.9 Initializing the Eureka-Server Context

serverContext.initialize();
logger.info("Initialized server context");
Copy the code
  • To initialize the Eureka-Server context, call the ServerContext#initialize() method:

    // DefaultEurekaServerContext.java @Override public void initialize() throws Exception { logger.info("Initializing ..." ); // Start the eureka-server cluster node set (replication) peerEurekaNodes. Start (); // Initialize registry. Init (peerEurekaNodes) for application instance information; logger.info("Initialized"); }Copy the code

2.2.10 Pull registration information from other Eureka-servers

// Copy registry from neighboring eureka node
int registryCount = registry.syncUp();
registry.openForTraffic(applicationInfoManager, registryCount);
Copy the code
  • This article does not expand to share, in “Eureka source code parsing – Eureka-server cluster synchronization” detailed analysis.

2.2.11 Registration Monitoring

// Register all monitoring statistics.
EurekaMonitors.registerAllStats();
Copy the code
  • Cooperate with Netflix Servo to realize monitoring information collection.

3. Filter

The eureka-server filters (javax.servlet.filter) are in the following order:

  • StatusFilter
  • ServerRequestAuthFilter
  • RateLimitingFilter
  • GzipEncodingEnforcingFilter
  • ServletContainer

3.1 StatusFilter

Com.net flix. Eureka. StatusFilter, eureka – Server status filter. If eureka-server is not in InstanceStatus.UP state, return HTTP status code 307 redirection as follows:

// StatusFilter.java private static final int SC_TEMPORARY_REDIRECT = 307; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { InstanceInfo myInfo = ApplicationInfoManager.getInstance().getInfo(); InstanceStatus status = myInfo.getStatus(); if (status ! = InstanceStatus.UP && response instanceof HttpServletResponse) { HttpServletResponse httpRespone = (HttpServletResponse) response; httpRespone.sendError(SC_TEMPORARY_REDIRECT, "Current node is currently not ready to serve requests -- current status: " + status + " - try another DS node: "); } chain.doFilter(request, response); }Copy the code

3.2 ServerRequestAuthFilter

Com.net flix. Eureka. ServerRequestAuthFilter, eureka – Server requests authentication filter. Eureka-server is not authenticated. At present, the client name and version number accessed are printed to realize monitoring information collection in cooperation with Netflix Servo. The implementation code is as follows:

// ServerRequestAuthFilter.java protected void logAuth(ServletRequest request) { if (serverConfig.shouldLogIdentityHeaders()) { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; String clientName = getHeader(httpRequest, AbstractEurekaIdentity.AUTH_NAME_HEADER_KEY); String clientVersion = getHeader(httpRequest, AbstractEurekaIdentity.AUTH_VERSION_HEADER_KEY); DynamicCounter.increment(MonitorConfig.builder(NAME_PREFIX + clientName + "-" + clientVersion).build()); }}}Copy the code

3.3 RateLimitingFilter

Com.net flix. Eureka. RateLimitingFilter, request through the filter. In “Eureka source code parsing — RateLimiter based on the token bucket algorithm” detailed parsing.

3.4 GzipEncodingEnforcingFilter

Com.net flix. Eureka. GzipEncodingEnforcingFilter, GZIP encoding filter.

3.5 ServletContainer

Com. Sun. Jersey. Spi. Container. Servlet. ServletContainer, jersey MVC request filter.

666. The eggs

Eureka-server startup complete!

Preparations are now complete for more interesting eureka-client/Eureka-Server interactions such as registration, renewal, cancellation, expiration, and so on.

Approach!

Fat friends, share a wave of friends can be good! ?