当前位置:网站首页>[issue 307] in terms of implementation principle, why is Nacos so strong?
[issue 307] in terms of implementation principle, why is Nacos so strong?
2022-04-22 10:17:00 【Java selection】
Click on the above “Java selected ”, choice “ Set to star ”
Don't ask people why , Ask yourself why !
below Have a pleasant surprise , A message will be back , Have a craigslist !
Make progress every day , It's the beginning of success ...
Nacos framework
Provider APP: Service providersConsumer APP: Serving consumersName Server: adopt VIP(Virtual IP) or DNS The way to achieve Nacos High availability cluster service routingNacos Server:Nacos Service providers , It contains Open API Is the function access portal ,Conig Service、Naming Service yes Nacos Configuration services provided 、 Name the service module .Consitency Protocol It's a consistency agreement , Used to implement Nacos Data synchronization of cluster nodes , What we use here is Raft Algorithm (Etcd、Redis Sentinel election )Nacos Console: Console
How the registry works
The service instance is registered to the service registry at startup , And log off on shutdown
The service consumer queries the service registry , Get available instances
The service registry needs to call the health check of the service instance API To verify that it can handle requests
SpringCloud Time to complete registration
stay Spring-Cloud-Common There is a class in the package org.springframework.cloud. client.serviceregistry .ServiceRegistry , It is Spring Cloud Standards for registration of services provided . Integrated into the Spring Cloud Components that implement service registration in , Will implement the interface .
The interface has an implementation class that is NacoServiceRegistry.
SpringCloud Integrate Nacos Implementation process :
stay spring-clou-commons Bag META-INF/spring.factories The configuration information of automatic assembly is as follows :
among AutoServiceRegistrationAutoConfiguration This is the configuration class related to service registration :
stay AutoServiceRegistrationAutoConfiguration Configuration class , You can see the injection of a AutoServiceRegistration example , The relationship diagram of this class is as follows .
It can be seen that , AbstractAutoServiceRegistration The abstract class implements the interface , And most importantly NacosAutoServiceRegistration Inherited AbstractAutoServiceRegistration.
notice EventListener We should know ,Nacos It's through Spring The event mechanism of inherits to SpringCloud Middle going .
AbstractAutoServiceRegistration Realized onApplicationEvent Abstract method , And monitor WebServerInitializedEvent event ( When Webserver After initialization ) , call this.bind ( event ) Method .
Will eventually call NacosServiceREgistry.register() Method to register the service .
NacosServiceRegistry The implementation of the
stay NacosServiceRegistry.registry In the method , Called Nacos Client SDK Medium namingService.registerInstance Complete service registration .
track NacosNamingService Of registerInstance() Method :
adopt
beatReactor.addBeatInfo()Create heartbeat information for health detection , Nacos Server You must ensure that the registered service instance is healthy , And heartbeat detection is the means to serve health testing .serverProxy.registerService()Implement service registration
heartbeat :
From the above code , The so-called heartbeat mechanism is that the client passes schedule Send a packet to the server regularly , Then start - A thread constantly detects the server's response , If no response is received from the server within the set time , The server fails .Nacos The server will update the service status according to the heartbeat packet of the client .
Registration principle :
Nacos Provides SDK and Open API There are two forms to implement service registration .
Open API:
SDK:
Both forms are essentially the same , The bottom is all based on HTTP The agreement completes the requested . So the registration service is to send a HTTP request :
about nacos Server side , The external service interface request address is nacos/v1/ns/instance, Implementation code nacos-naming Under the module of InstanceController Class :
Get... From the request parameter summary serviceName( service name ) and namespaceId( Namespace Id)
call registerInstance Registration instance
Create a control service ( stay Nacos Console “ List of services ” Service information displayed in ), It's actually initializing a serviceMap, It's a ConcurrentHashMap aggregate
getService, from serviceMap According to the namespaceId and serviceName Get a service object
in addition , official account Java selected , About springcloud Interview questions , reply java interview , Obtain interview question information .
call addInstance Add service instance
according to namespaceId、serviceName From the cache Service example
If Service Instance is empty , Then create and save to the cache
adopt
putService()Method to cache the service into memoryservice.init()Set up a heartbeat mechanismconsistencyService.listenAchieve data consistency monitoring
service.init ( ) The method is shown in the figure below , It continuously detects the time when all instances in the current service last send heartbeat packets through scheduled tasks . If the timeout , Is set healthy by false Indicates that the service is unhealthy , And send service change events .
Here, please think about one question , Who triggered the last heartbeat packet update time of the service instance ? In fact, I mentioned earlier , Nacos While the client registers the service, it also establishes a heartbeat mechanism .
putService Method , Its function is to Service Save to serviceMap in :
Continue to call addInstance Method to save the currently registered service instance to Service in :
summary :
Nacos Client pass Open API Send a service registration request in the form of
Nacos After the server receives the request , Do the following three things :
Construct a Service Object to save to ConcurrentHashMap Collection
Use a scheduled task to establish a heartbeat detection mechanism for all instances under the current service
Service data is synchronized based on data consistency protocol
Service provider address query
Open API:
SDK:
InstanceController Medium list Method :
Parse request parameters
adopt doSrvIPXT Return service list data
according to namespaceId、serviceName get Service example
from Service The example is based on srvIPs Get all service provider instances
Traversal assembly JSON String and return
Nacos Dynamic sensing principle of service address
Can pass subscribe Method to implement listening , among serviceName Indicates the service name 、EventListener Indicates the monitored event :
The specific calling method is as follows :
Or call selectInstance Method , If you will subscribe Property is set to true, Will automatically register to listen :
Nacos There is one in the client HostReactor class , Its function is to realize the dynamic update of services , The basic principle is :
After the client initiates the subscription , stay HostReactor There is one of them. UpdateTask Threads , Every time 10s Send it once Pull request , Get the latest address list of the server
For the server , Heartbeat detection is maintained between it and the instance of the service provider , Once the service provider has an exception , Will send a Push A message to Nacos client , That is, service end consumers
After the service consumer receives the request , Use HostReactor Provided in processServiceJSON Parsing message , And update the local service address list
author : Wu Shengzi night song
https://blog.csdn.net/cold___play/article/details/108032204
official account “Java selected ” The published content indicates the source of , All rights reserved ( Those whose copyright cannot be verified or whose source is not indicated all come from the Internet , Reprinted , The purpose of reprinting is to convey more information , The copyright belongs to the original author . If there is any infringement , Please contact the , The author will delete the first time !
------ THE END ------
Excellent materials , Great benefits !
* Main stream Java Advanced technology ( Learning material sharing )
>Java Interview questions <
3000+ Brush all kinds of technical interview questions online , newest 、 The most complete Java Interview questions !


Hope to select Click on the title to jump to
【299 period 】Spring Boot exception handling , Worth learning !
【300 period 】Spring Boot Summary of date and time formatting processing methods
【301 period 】SpringBoot One interface supports both form、form-data、json Elegant writing
【302 period 】SpringBoot Project authentication 4 Ways of planting , Do you understand? ?
【304 period 】 Full text search engine Elasticsearch, This article tells me the whole story !
【305 period 】Spring Cloud Elegant offline + Grayscale Publishing
technology Communication group !
Many people have asked recently , Is there any readers Communication group ! Want to know how to join ? It's very simple , Friends with similar interests , Just click on the card below , reply “ Add group ”, that will do No routine Join the communication group !
If the article helps , Looking at , Forward! !
版权声明
本文为[Java selection]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221013458866.html
边栏推荐
- [C language advanced level 10 -- character and string functions and their simulation implementation (1)]
- Deep learning remote sensing scene classification data set sorting
- 企业级 Web 开发的挑战
- 分表和分区的区别
- 頭條面試居然跟我扯了半小時的Semaphore
- 企业级 Web 开发的挑战
- linux7静默安装oracle11g
- 三分钟快速了解互动涂鸦
- Generalized Robust Regression for Jointly Sparse Subspace Learning
- Glide设置圆角图片(支持自定义圆角位置)
猜你喜欢

JWT source code analysis (four layer package with schematic diagram)

头条面试居然跟我扯了半小时的Semaphore

基于SSM的电影在线购票系统

Various location codes applied in transformer model

CLA: silver bullet to reduce the compliance risk of open source community?

頭條面試居然跟我扯了半小時的Semaphore

Usage of stringstream

01背包问题——以及变形问题

The working principle of triode, FET and MOS transistor

Simple operation of QT axobject Library
随机推荐
Zhezheng nail scanning code login
Matplotlib tutorial 04 --- drawing commonly used graphics
oracle19. 3 upgrade to 19.6
企业级 Web 开发的挑战
J'ai eu un entretien d'une demi - heure avec Semaphore.
Generalized Robust Regression for Jointly Sparse Subspace Learning
Analysis of image lazy loading (three implementation methods and two optimization methods)
QT event filter instance
Creating student management system with MySQL
Dext diagnostic database supporting AUTOSAR classic and adaptive platform
基于SSM的电影在线购票系统
Cross platform compilation
Usage of stringstream
Simple operation of QT axobject Library
Difference between sub table and partition
辐射度量学基本概念
Nacos
【无标题】
The working principle of triode, FET and MOS transistor
[SQL Server] SQL overview