In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
What this article shares with you is how to understand the service model. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it with the editor.
Preface
According to the current mainstream usage scenarios in the market, Nacos is divided into two functions: service Registration Discovery (Naming) and configuration Center (Config). In the previous article, I introduced the implementation principle of the Nacos configuration center, and today's article is related to the Nacos service registration discovery feature to talk about the service model of Nacos.
When it comes to the service model, in fact, we need to distinguish between the perspective, one is the user perspective, a kernel perspective. That is, the service model seen from the Nacos user perspective may be completely different from the kernel model designed by Nacos developers, while today's article aims to explore the best practices of Nacos service discovery from a user perspective.
Introduction of service model
Usually when I talk about registration centers, I will use Zookeeper as the introduction, which is also the most familiar registration center for many people. But if you have really written or read the adaptation code that uses Zookeeper as the registry, you will find that it is not so easy, coupled with the consistency principle involved in the registry, which leads to many people's first impression of the registry is: this thing is so difficult! But in the final analysis, because Zookeeper is not specifically designed for registries, the API and kernel design it provides does not set aside the concept of a "service model", which makes developers need to design a model to bridge the gap between Zookeeper and service discovery.
After the micro-service architecture has gradually taken root in the hearts of the people, registry components such as Nacos, Consul, Eureka and so on have entered the attention of the public. It can be found that these "real" registries have their own "service models" and are more convenient to use.
Why is there a "service model"? In theory, a basic component can be shaped into anything, and a database can be designed as a registry if you like, which is not an "exaggerated" figure of speech. Some people have done this in Ali. So what's the price? After the business develops to a certain volume, it will encounter a bottleneck, and some extreme case will cause it to fail to work properly, which will lead to its low scalability. Just like a common question among students when they first learned the data structure: why the stack can only go in first and then out later. Not all developers are middleware experts, so Nacos designed its own "service model", which limits the "imagination" of users, but ensures that users are using Nacos correctly.
Spend some space on why Nacos needs to design a "service model", and then take a look at what the actual Nacos model is. In fact, it is not so mysterious, it can be expressed clearly in a single picture:
Unlike Consul and Eureka designs, the domain model used by Nacos service discovery is a multi-tier structure such as namespace-grouping-service-cluster-instance. Service Service and instance Instance are the core models, while namespace Namespace, grouping Group, and cluster Cluster implement service isolation at different granularities.
In order to better understand the two core models: Service and Instance, we take Dubbo and SpringCloud, two micro-service frameworks that have adapted to the Nacos registry, as an example to introduce how they map the corresponding model.
Dubbo . Map the interface triple (interface name + grouping name + version number) to Service, and define the instance IP and port number as Instance. A typical Dubbo service registered in Nacos: providers:com.alibaba.mse.EchoService:1.0.0:DUBBO
Spring Cloud . Map the application name to Service, and define the instance IP and port number as Instance. A typical Spring Cloud service registered in Nacos: helloApp
Below we will explain in more detail the relationship between the API and the service model provided by Nacos.
Environmental preparation
Need to deploy a Nacos Server for testing, I choose to directly in the
Https://mse.console.aliyun.com/ buys a MSE-hosted Nacos, and readers can choose to buy MSE Nacos or build their own Nacos Server.
The visual console provided by MSE Nacos can also help us better understand the service model of Nacos. Some of the screenshots below are from the commercialization console of MSE Nacos.
Quick start
Let's first implement the simplest service registration and discovery demo. Nacos supports registering service instances and subscribing to services from the client, as shown below:
Properties properties = new Properties (); properties.setProperty (PropertyKeyConst.SERVER_ADDR, "mse-xxxx-p.nacos-ans.mse.aliyuncs.com:8848"); String serviceName = "nacos.test.service.1"; String instanceIp = InetAddress.getLocalHost (). GetHostAddress (); int instancePort = 8080 controlling Service.registerInstance (serviceName, instanceIp, instancePort); System.out.println (namingService.getAllInstances (serviceName))
The above code defines a service:nacos.test.service.1; and an instance, and uses native host as IP and 8080 as port number to observe the actual registration:
And the console prints out the details of the service. At this point, one of the simplest Nacos service discovery demo is complete. Explain a little bit about some details:
The property PropertyKeyConst.SERVER_ADDR represents the address of the Nacos server.
Create a NamingService instance for which the client will create a separate resource space, including cache, thread pool, configuration, and so on. The Nacos client does not have a singleton restriction on this instance. Please maintain this instance carefully in case you create more than expected instances.
The registration service registerInstance uses the simplest overloading method by passing in the service name, IP, and port.
In the above examples, the service models mentioned above do not appear, such as Namespace, Group, Cluster, and so on. I will describe them in detail in the following section. This example is mainly to demonstrate some of the default configurations supported by Nacos, in which Service and Instance are essential, which also verifies that the services and instances mentioned above are first-class citizens of Nacos.
By taking a screenshot, we can find the default values for the default configuration:
Namespace: the default value is public or an empty string, which can represent the default namespace.
Group: the default is DEFAULT_GROUP.
Cluster: the default is DEFAULT.
Build a custom instance
In order to show the full picture of the Nacos service model, you also need to introduce the instance-related API. For example, some of the registered instances can be allocated more traffic, or the meta-information of some instances can be stored in the Nacos server, such as the application to which IP belongs or the data center where the server resides, so that the client can customize the load balancing mode based on the meta-information of the instance mounted under the service. Nacos also provides another API for registering an instance, so that users can specify the properties of the instance when registering the instance:
/ * register an instance to service with specified instance properties. * * @ param serviceName name of service * @ param groupName group of service * @ param instance instance to register * @ throws NacosException nacos exception * / void registerInstance (String serviceName, String groupName, Instance instance) throws NacosException
When registering an instance, this method can pass in an Instance instance with the following properties:
Public class Instance {/ * * unique id of this instance. * / private String instanceId; / * * instance ip. * / private String ip; / * * instance port. * / private int port; / * * instance weight. * / private double weight = 1.0D; / * * instance health status. * / private boolean healthy = true; / * * If instance is enabled to accept request. * / private boolean enabled = true; / * * If instance is ephemeral. * * @ since 1.0.0 * / private boolean ephemeral = true; / * * cluster information of instance. * / private String clusterName; / * * Service information of instance. * / private String serviceName; / * * user extended attributes. * / private Map metadata = new HashMap ();}
Some fields are literal, while others take some effort to understand the design of Nacos. I'll highlight a few attributes that I think are important:
Health status of healthy instance. This field is automatically updated by the general heartbeat health check to identify whether the instance is healthy.
Whether enable is enabled. It is different from healthy in that healthy is generally updated by kernel health check, while enable is more business semantic and can be manipulated entirely according to business scenarios. For example, in Dubbo, this field is generally used to identify the online and offline status of an instance IP.
Ephemeral temporary instance or persistent instance. A very critical field, you need to have a more in-depth understanding of Nacos to understand the meaning of this field. The difference is whether the instance is automatically logged off or marked as unhealthy after the heartbeat detection fails for a certain period of time. In general, temporary instances are used in registry scenarios. In this way, when heartbeat detection fails, consumers can receive offline notification in time, while in DNS mode, persistence instances are used more frequently. As I mentioned in "detailed description of Nacos's high availability features", this field also affects the conformance protocol of Nacos.
Metadata metadata. A map structure that can store custom extension information of instances, such as computer room information, routing labels, application information, weight information, and so on.
After the information is reported by the service provider, it is obtained by the service consumer to complete the transmission of the information. The following is a complete example registration demonstration code:
Properties properties = new Properties (); / / specify the Nacos Server address properties.setProperty (PropertyKeyConst.SERVER_ADDR, "mse-xxxx-p.nacos-ans.mse.aliyuncs.com:8848"); / / specify the namespace properties.setProperty (PropertyKeyConst.NAMESPACE, "9125571e-bf50-4260-9be5-18a3b2e3605b"); NamingService namingService = NacosFactory.createNamingService (properties); String serviceName = "nacos.test.service.1"; String group = "DEFAULT_GROUP"; String clusterName = "cn-hangzhou" String instanceIp = InetAddress.getLocalHost (). GetHostAddress (); int instancePort = 8080 X instance instance = new Instance (); / / specify the cluster name instance.setClusterName (clusterName); instance.setIp (instanceIp); instance.setPort (instancePort); / / metadata of the specified instance Map metadata = new HashMap (); metadata.put ("app", "nacos-demo"); metadata.put ("site", "cn-hangzhou"); metadata.put ("protocol", "1.3.3"); instance.setMetadata (metadata) / / specify service name, grouping and instance namingService.registerInstance (serviceName, group, instance); System.out.println (namingService.getAllInstances (serviceName))
Build a custom service
In addition to instances, services can also be customized, and Nacos services exist with the registration of instances and die with the logout of all instances. However, Nacos does not support custom services very well. Except that you can modify the attributes of services using OpenApi, you can only use the attributes passed when registering the instance to customize the configuration. Therefore, in the actual Dubbo and SpringCloud, custom services are generally less used, while custom instance information is relatively common.
The service of Nacos is different from the model of Consul and Eureka. The service of Consul and Eureka is equivalent to the instance of Nacos. Each instance has a service name attribute, and the service itself is not a separate model. The design of Nacos seems more reasonable to me, because it believes that the service itself also has data storage requirements, such as configuration and permission control for all instances under the service. The properties of the instance should be inherited from the properties of the service, and the instance level can override the service level. The following is the data structure of the service:
/ * Service name * / private String name; / * Protect threshold * / private float protectThreshold = 0.0F; / * Application name of this service * / private String app; / * Service group which is meant to classify services into different sets. * / private String group; / * * Health check mode. * / private String healthCheckMode; private Map metadata = new HashMap ()
In actual use, you can simply tag a service with ServiceName, as described in the Quick start section.
Service isolation: Namespace&Group&Cluster
For space reasons, these three concepts are introduced together.
The king is intentional, but the goddess is unintentional. Nacos proposed these isolation strategies. At present, only Namespace is widely used in practical applications, while Group and Cluster are not taken seriously.
Cluster cluster isolation is commonly used within Alibaba. A typical scenario is an instance under this service, which needs to be configured with multiple health check methods. Some instances use TCP health check method, while others use HTTP health check method. In another scenario, the machines mounted under the service belong to different environments. It is hoped that all the traffic in a certain environment can be cut off in some cases, so that the flow can be cut at one time through cluster isolation. In Nacos 2.0, we are also deliberately weakening the concept of cluster. after all, open source still has to be user-oriented, and some things are suitable for Ali, but not necessarily for open source. After further evolution, the concept of cluster may come back to everyone's attention, history will repeat itself.
The concept of Group packet isolation can refer to Dubbo's service isolation policy, which also has a packet. Of course, it is well-intentioned to support the expansion of grouping, and in practice, some companies are used to using grouping for isolation. It should be noted that when Dubbo registers a triple (API name + grouping + version), the packet of Dubbo is included in the service name of Nacos and is not mapped to the packet of Nacos. Generally, services registered by Nacos are registered to DEFAULT_GROUP packet by default.
Namespace namespace isolation, which I think is a better design for Nacos. It is also widely used in real scenes, and it is generally used for the isolation of multiple environments, such as daily,dev,test,uat,prod and other environments. Especially when there are a lot of environments, using namespaces for logical isolation is a cost-saving strategy. However, it is strongly recommended that you only use Namespace for isolation in non-online environments. For example, multiple test environments can share a set of Nacos, while online environments build another Nacos cluster separately to prevent offline test traffic from interfering with the online environment.
Service Discovery: push-pull Model
The above introduces the five domain models of Nacos service discovery, and the last section describes how to obtain the service model.
Nacos's service discovery has two modes: active pull and push, which is the same as the general service discovery architecture. The following are the relevant interfaces of the pull model:
/ * Get all instances of a service * * @ param serviceName name of service * @ return A list of instance * @ throws NacosException * / List getAllInstances (String serviceName) throws NacosException;/** * Get qualified instances of service * * @ param serviceName name of service * @ param healthy a flag to indicate returning healthy or unhealthy instances * @ return A qualified list of instance * @ throws NacosException * / List selectInstances (String serviceName, boolean healthy) throws NacosException / * Select one healthy instance of service using predefined load balance strategy * * @ param serviceName name of service * @ return qualified instance * @ throws NacosException * / Instance selectOneHealthyInstance (String serviceName) throws NacosException
Nacos provides three methods to pull services synchronously, one is to query all registered instances, one is to query only healthy and online instances, and the other is to obtain a healthy and online instance. In general, subscribers do not care about unhealthy instances or instances whose weight is set to 0, but it does not rule out that in some scenarios, some OPS or managed scenarios need to get all the instances. Careful readers will notice that there is a weight field in the above Nacos instance, which acts on the selectOneHealthyInstance interface here and returns a healthy instance according to weight. Personally, I think this feature is relatively chicken. General RPC frameworks have their own supporting load balancing strategies, which are rarely cover by the registry. In fact, neither Dubbo nor Spring Cloud use this interface of Nacos.
In addition to actively querying the instance list, Nacos also provides a subscription model to perceive changes in the instance list under the service, including changes in service configuration or instance configuration. You can use the following interfaces to subscribe or unsubscribe:
/ * Subscribe service to receive events of instances alteration * * @ param serviceName name of service * @ param listener event listener * @ throws NacosException * / void subscribe (String serviceName, EventListener listener) throws NacosException;/** * Unsubscribe event listener of service * * @ param serviceName name of service * @ param listener event listener * @ throws NacosException * / void unsubscribe (String serviceName, EventListener listener) throws NacosException
In the actual service discovery, the subscription interface is particularly important. When consumers start up, they usually synchronously obtain service information for initialization, and then subscribe to the service, so that when the service is online and offline, it can perceive changes and realize service discovery.
The above is how to understand the service model. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.