当前位置:网站首页>Nacos series registry principle and source code analysis
Nacos series registry principle and source code analysis
2022-06-13 05:40:00 【codain】
1、 How the registry works
The main functions of service registration are mainly reflected in the following three points :
① The registered instance can be registered to the service center when the service is started , When the service is shut down, it will be revoked from the registry
② Consumers can get available instances in the registry
③ The registry will call the health check API To regularly verify whether the services on the current registry are normal , To determine whether the request can be processed
2、 Reading Nacos Source code :
About source code analysis , We don't have to look at it all , Let's just look at the three key parts : Service registration 、 Service address acquisition 、 The perception of service address change is sufficient
2.1 Service registration
1、 stay Cloud There is a class named ServiceRegistry Interface class of , He is springcloud Provide a standard for service registration , As long as it is integrated into springcloud Components that implement service registration in , We need to implement this interface
package org.springframework.cloud.client.serviceregistry; public interface ServiceRegistry<R extends Registration> { void register(R registration); void deregister(R registration); void close(); void setStatus(R registration, String status); <T> T getStatus(R registration); }
2、 Next , Let's take a look at the implementation 1 Methods of interface classes in NacosServiceRegistry, See when it was registered
public void register(Registration registration) { if (StringUtils.isEmpty(registration.getServiceId())) { log.warn("No service to register for nacos client..."); } else { String serviceId = registration.getServiceId(); String group = this.nacosDiscoveryProperties.getGroup(); Instance instance = this.getNacosInstanceFromRegistration(registration); try { // Implement registration this.namingService.registerInstance(serviceId, group, instance); log.info("nacos registry, {} {} {}:{} register finished", new Object[]{group, serviceId, instance.getIp(), instance.getPort()}); } catch (Exception var6) { log.error("nacos registry, {} register failed...{},", new Object[]{serviceId, registration.toString(), var6}); } } }
Take a look at how to register
public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException { if (instance.isEphemeral()) { BeatInfo beatInfo = new BeatInfo(); beatInfo.setServiceName(NamingUtils.getGroupedName(serviceName, groupName)); beatInfo.setIp(instance.getIp()); beatInfo.setPort(instance.getPort()); beatInfo.setCluster(instance.getClusterName()); beatInfo.setWeight(instance.getWeight()); beatInfo.setMetadata(instance.getMetadata()); beatInfo.setScheduled(false); long instanceInterval = instance.getInstanceHeartBeatInterval(); beatInfo.setPeriod(instanceInterval == 0L ? DEFAULT_HEART_BEAT_INTERVAL : instanceInterval); // Create heartbeat information to realize health monitoring this.beatReactor.addBeatInfo(NamingUtils.getGroupedName(serviceName, groupName), beatInfo); } // Implement service registration this.serverProxy.registerService(NamingUtils.getGroupedName(serviceName, groupName), groupName, instance); }
I won't talk about the heartbeat , It's very simple , Heartbeat is actually a data packet that the client sends a request for registration information to the server through a scheduled task , Then start a special detection service , Then there is the default 15 One second detection ,30 Second culling mechanism , There is nothing more to say , Then we will continue to look at the registerService What did the method do
public void registerService(String serviceName, String groupName, Instance instance) throws NacosException { LogUtils.NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}", new Object[]{this.namespaceId, serviceName, instance}); Map<String, String> params = new HashMap(9); params.put("namespaceId", this.namespaceId); params.put("serviceName", serviceName); params.put("groupName", groupName); params.put("clusterName", instance.getClusterName()); params.put("ip", instance.getIp()); params.put("port", String.valueOf(instance.getPort())); params.put("weight", String.valueOf(instance.getWeight())); params.put("enable", String.valueOf(instance.isEnabled())); params.put("healthy", String.valueOf(instance.isHealthy())); params.put("ephemeral", String.valueOf(instance.isEphemeral())); params.put("metadata", JSON.toJSONString(instance.getMetadata())); this.reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, (String)"POST"); }
It's very simple , Just use Map It encapsulates the registered address and other information , Last in use reqAPI, One nacos Provide registered API Interface to implement service registration , If you are interested in children's shoes, you can check them out nacos Providing service registration API Source code , Let's see InstanceController The control class , This is the interface class mainly implemented , You can give a brief overview of the main tasks of this interface :
①Nacos Client pass API Send a service registration request in the form of , Request this class , This class is responsible for receiving registration requests
② After receiving the request , Construct a service Object to save to Map Collection
③ Use a scheduled task to create a heartbeat detection mechanism for all current instances
④ The data consistency protocol synchronizes the data of the service
After parsing the above registration principle and source code , In fact, you can also know the encapsulation of the input parameters of the previous series of operations , The key is to call nacos Provided API Registration is realized , Let's think about other things API How did it happen ? For example, query the address information of the service API, If you are interested , You can study it , You'll find that , The code is very simple and interesting
边栏推荐
- SQL table columns and statements of database
- Unity游戏优化[第二版]学习记录6
- MySQL fuzzy query and sorting by matching degree
- 通过命令行创建harbor镜像库
- [reprint] complete collection of C language memory and character operation functions
- Course outline of market drawing 1- basic knowledge
- One of PowerShell optimizations: prompt beautification
- Etcd understanding of microservice architecture
- First assessment
- Compilation croisée helloworld avec cmake
猜你喜欢
[China & some provinces and cities] JSON file for offline map visualization
2 first experience of drools
890. Find and Replace Pattern
1 Introduction to drools rule engine (usage scenarios and advantages)
powershell优化之一:提示符美化
Byte buddy print execution time and method link tracking
890. Find and Replace Pattern
MySQL fuzzy query and sorting by matching degree
KVM hot migration for KVM virtual management
Metartc4.0 integrated ffmpeg compilation
随机推荐
mongo
使用cmake交叉編譯helloworld
Difference between deviation and variance in deep learning
安装harbor(在线|离线)
Mysql database crud operation
Solutions to conflicts between xampp and VMware port 443
Pycharm错误解决:Process finished with exit code -1073741819 (0xC0000005)
[reprint] complete collection of C language memory and character operation functions
Float type value range
Mongodb multi field aggregation group by
Case - the ArrayList collection stores student objects and traverses them in three ways
MySQL advanced query
890. Find and Replace Pattern
MySQL basic query
16 the usertask of a flowable task includes task assignment, multi person countersignature, and dynamic forms
Enhanced for loop
Use of mongodb
Compilation croisée helloworld avec cmake
Unity game optimization (version 2) learning record 7
Create a harbor image library from the command line