In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to achieve a Nacos registry". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to achieve a Nacos registry".
What is Nacos?
A dynamic service discovery, configuration management and service management platform that is easier to build cloud native applications.
The popular explanation is: Nacos is a registry center & configuration center.
Key characteristics
Service discovery and service health monitoring
Dynamic configuration service
Dynamic DNS service
Service and its metadata management
For more details, please refer to the Nacos official documentation.
What is a registry?
We say that Nacos is a registry, so what is a registry? Through the above key features is not difficult to find, the registry provides service registration, service discovery, service health check and other basic capabilities, so that developers can easily manage services, in the Spring Cloud family, representative of Spring Cloud Eureka, Spring Cloud Consul, and early Apache Zookeeper, these can be called registries, if the partners who have not been in contact with micro services before may have doubts, why do you need a registry?
The Origin of Registration Center
Let's first take a look at the most primitive way of calling between services.
Http remote call
It is believed that this is the simplest and most familiar way of calling. In the same company, when A project team (order service for short) wants to use the capabilities provided by B project team (commodity service for short), it often uses this way to simply send a Http request to obtain the capabilities of the other party.
This approach is relatively simple, but there are also some problems, such as:
When the merchandise service makes the service migration, the order service will have to change the request address and then restart the service
When the commodity service is clustered, the order service needs to have a load balancing strategy, otherwise it will cause excessive pressure on the single node of the commodity service.
At this time, friends with development experience will say: just do a Nginx to do load balancing! Yes, when the service goes to the production environment, we all change it this way.
Nginx load
Based on the problem of direct invocation of Http request, we only need to change the calling policy slightly: add a Nginx in the middle, and the order service no longer calls the commodity service directly, and accesses the Nginx, which is forwarded to the commodity service by Nginx. At this time,
If the ip address of goods and services is changed: just change the proxy configuration of Nginx.
If the capacity of goods and services is scaled down, you can change the load balancer configuration of Nginx.
Perfectly solve the problem of direct call of Http request
Generally speaking, ordinary projects are fine here, but with the continuous iteration of the business, the capacity required gradually increases. At this time, there are not only orders and commodity services, but also logistics, points, inventory, payment and other services. not only that, these services and services will also transfer each other, order transfer points, logistics transfer inventory, order transfer payment. At this point, the invocation between the service and the service looks like this:
It is not difficult to imagine that the Nginx configuration at this time will move every operation and maintenance brother. After each service configuration change, or add a service, the operation and maintenance brother's heart will tremble.
Until one day, developer: add another service today.
In the previous company, A Jian had the honor to witness what the nginx looked like when the operation and maintenance brother configured the service. The configuration of the three nginx was full and made the scalp numb. I wonder if any of my friends have ever encountered this kind of situation.
Use MySQL to record address information
Using Nginx load is indeed a better way, but there are some operation and maintenance brothers, we might as well think about it, except that the operation and maintenance brothers know the address information of the service, who else knows?
Yes, it is the service itself!
We convert the operation and maintenance brother's action of configuring the service address to insert a piece of data into the MySQL when the service is started.
The action of Nginx route forwarding is changed to: the order service queries the address of the commodity service in the database, and then initiates the call.
Nginx load balancer is changed to: order service query the list of goods and services, and choose one of the addresses.
The way it is changed is shown in the following figure:
There is a server_name field in the table structure, which can be queried using server_name='goods-server' when invoking goods and services.
In this way, we can kaichu the operation and maintenance brother.
It is not difficult for thoughtful friends to see the problems:
All services need to connect to this MySQL, and once MySQL is on his knees, so are we.
The MySQL needs to be queried each time the service initiates the call.
If the service dies, the record in MySQL still exists.
So let's start to solve these problems now.
Since MySQL doesn't work, let's change it to Redis. It's not realistic to have a MySQL for all services, even Redis.
You need to query it once before each call, and cache it locally after the query. At the same time, start the scheduled task, update the cache every 30 seconds, and obtain address information from the cache when the service is called.
If the service dies, the record in the MySQL still exists: the data inserted into the Redis will expire, and the timing task will be started after the service starts, and the cache will be updated every 30 seconds. If the service fails, the cache will expire automatically.
Hey, now we are looking at this plan, is it more perfect?
Tell your partner secretly that this is how Dubbo plays when he uses Redis as a registry.
Although it looks perfect, when the second and third points are actually used, the problems are enough to make people autistic. Now A Jian gives you a simulation of the autistic scene.
Environment: order service: one instance, merchandise service, two instances, An and B.
Time: 1 minute 00 seconds
Order service calls merchandise service, normal.
A goods and services cache expiration time remaining: 29s
Time: 1 minute 01 seconds
A goods and services synchronize Redis cache information, the remaining expiration time of Redis: 30s.
At the same time, A goods and services are offline (hang up)
Time: 1 minute 02 seconds
The order service invokes the merchandise service. Because the A merchandise service has been offline, the invocation is good and bad (it is normal when calling B).
A goods and services in the local cache expiration time remaining: 28s
A goods and services Redis remaining expiration time: 29s
Time: 1 minute 29 seconds
Local cache update, refresh A commodity service cache time: 30s
A goods and services Redis remaining expiration time: 1s, expire in the next second
Time: 1 minute 59 seconds
Update the local cache to refresh the A merchandise service cache: there is no A merchandise service information in the Redis cache, so the A merchandise service information will no longer exist in the local cache.
The order service calls the commodity service, which is normal (at this time, there is only B goods and service information in the cache)
Simulation completed
As you can see, at 1 minute 01 seconds, the A commodity service has been offline, but it is not until 1 minute 59 seconds that the order service can be reflected. Among them, 58 seconds of service calls are good and bad, what if it is enough to make people autistic in the production environment.
Of course, if you add a retry strategy to the order service: after the failure of invoking the A commodity service, retry and call the B commodity service, you can better solve this problem, but assuming that the A commodity service does not hang up, it just shakes for a moment, and the order service invokes the B commodity service again, which is equivalent to adjusting the interface twice at the same time. At this time, you have to consider the idempotence of the interface.
At this time, some friends may say: what is the problem of idempotency, Easy! However, the level of developers in a project is uneven, and it is unrealistic to require everyone to do it. Stop talking and be sprayed if you talk too much.
The crux of this question is whether the caller can perceive the change in time when the called service is dead.
Hey, the earliest Zookeeper (referred to as zk) is the temporary node mechanism of zk, which is used to do this job, so that after the service is offline, zk can immediately perceive, and watch mechanism can make other services receive changes in the monitored data immediately. If there is too much content, A Jian will no longer talk about it here. Interested partners can do some research on their own, Zookeeper's official website.
Registration center
After talking so much, I believe our partners already have some feelings about what a registry is. Yes, the above are the capabilities of a registry. When we abstract these capabilities into a service, then this service is called a registry!
The picture painted by Ah Jian below is still a little good-looking.
As you can see, the registry has four basic interfaces: service registration, service discovery (acquisition), heartbeat detection, and service logout.
The following is the procedure for invoking the service when using the registry
Order service | when the merchandise service starts, call the service registration API to send your address information to the registry
When the order service invokes the commodity service, it invokes the service acquisition API to obtain the address information of the commodity service and put it in the cache.
Use the calling component for load balancing and initiate the call
The merchandise service is offline, the service logout API is called, and the registry removes the commodity service information.
Of course, this method still fails to solve the problem of whether the called service is dead, whether the caller can perceive the change in time, and how to solve it. Let's talk about it later.
I believe my partner has understood the principle of a registry, so now let's write a registry by hand and start using Nacos.
Nacos installation
Nacos supports three deployment models
Stand-alone mode-for testing and stand-alone trial.
Cluster mode-used in production environments to ensure high availability.
Multi-cluster mode-for multi-data center scenarios.
Stand-alone mode
Environment: Ubuntu 18.04LTS
Download the installation package
Releases notes
Select version 1.4.2 here
Wget https://github.wuyanzheshui.workers.dev/alibaba/nacos/releases/download/1.4.2/nacos-server-1.4.2.tar.gztar-xf nacos-server-1.4.2.tar.gz configuration
Nacos supports two data storage methods.
Use built-in data sources to store data, and you can start Nacos directly in this way
Use MySQL for data storage, which requires a MySQL first
To make it easier to observe the basic situation of data storage, we use the MySQL storage method here.
Change, create a MySQL, partners without MySQL can refer to install MySQL
Execute initialization SQL script
Script address
Modify the configuration file
Vim nacos/conf/application.properties
Spring.datasource.platform=mysql### Count of DB:db.num=1### Connect URL of DB:db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTCdb.user.0=nacosdb.password.0=nacosnacos.core.auth.enabled=truenacos.core.auth.enable.userAgentAuthWhite=falsenacos.core.auth.server.identity.key=abcdnacos.core.auth.server.identity.value=123456
The db-related configuration is modified to its own MySQL configuration, and nacos.core.auth.server.identity.key and nacos.core.auth.server.identity.value are defined by themselves.
Start bash nacos/bin/startup.sh-m standalone
Ubuntu systems need to use the bash command, while other systems can use the sh command
At this point, enter the following address in the browser to open the Nacos console
127.0.0.1:8848/nacos/index.html
The initial account password is: nacos | nacos
Cluster mode
Environment: Ubuntu 18.04 LTS three, the addresses are:
192.168.2.11:8848
192.168.2.12:8848
192.168.2.13:8848
No three partners can set up a pseudo-cluster for testing, such as 127.0.0.1lax 8848127.0.1purl 8849127.0.0.1purl 8850
It is very easy to build a cluster mode. The specific steps are as follows:
Copy three copies of the configuration of stand-alone mode to each node
Create a new cluster.conf under the conf folder of each node and configure it as follows
192.168.2.11:8848192.168.2.12:8848192.168.2.13:8848
Start each node in turn
Bash startup.sh
In this way, the nacos cluster is set up, but we also need a nginx for load balancing when accessing the browser.
Change into a nginx. If you don't have a nginx, you can refer to install Nginx.
Configure reverse proxy
Server {listen 8850; server_name _; location / {proxy_pass http://nacos-server;}} upstream nacos-server {server 192.168.2.13 server_name 8848 weight=5; server 192.168.2.12 server_name 8848 weight=5; server 192.168.2.11
Visit
Since my Nginx is on 192.168.2.11, my access address is: 192.168.2.11:8848/nacos. The initial account password is the same as the stand-alone mode: nacos | nacos
Nacos Spring Cloud
The Nacos has been built, and the next step is to use it.
Next, A Jian will show you how to use Nacos in the Spring Cloud project.
Basic use of new projects
Create a new my-micro-service-demo project and add Spring Cloud related dependencies to pom.xml
1.8 Hoxton.SR8 2.2.5.RELEASE org.springframework.cloud spring-cloud-dependencies ${spring.cloud-version} pom import com.alibaba.cloud spring-cloud-alibaba-dependencies ${spring.cloud.alibaba-version} pom import
Add two sub-modules to the project, my-order and my-goods, and introduce the dependency of Nacos
Com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery
Write bootstrap.yaml configuration file
Server: port: 8080spring: application: name: my-order main: allow-bean-definition-overriding: true cloud: nacos: discovery: server-addr: 192.168.2.11 username 8850 username: nacos password: nacosmanagement: endpoints: web: exposure: include: "*"
Goods and services can be changed by changing the service name and port number.
Write startup classes
Package com.my.micro.service.order;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * @ author Zijian Liao * @ since 1.0.0 * / @ SpringBootApplicationpublic class OrderApplication {public static void main (String [] args) {SpringApplication.run (OrderApplication.class, args);}}
Start the project and view the Nacos console
Service registered successfully
Initiate a call
Now that the service is registered with Nacos, let's try to invoke the merchandise service using the order service.
In the schematic diagram, the order service is a calling component that is used to invoke the commodity service. You don't have to care about what the calling component is, and A Jian will explain it in detail in the following articles.
Write an interface in a commodity service
@ RestController@RequestMapping ("/ goods") public class GoodsController {@ GetMapping ("/ get") public String get () {return "goods and services respond to an Apple";}}
Inject invocation components into the order service
@ LoadBalanced @ Bean public RestTemplate restTemplate () {return new RestTemplate ();}
The addition of @ LoadBalanced annotation will increase the ability of RestTemplate to make calls based on service name
Initiate a call
@ RestController@RequestMapping ("/ order") public class OrderController {@ Resource private RestTemplate restTemplate; @ GetMapping ("/ get") public String get () {/ / Old way: restTemplate.getForObject ("http://127.0.0.1:8081/goods/get", String.class) / / now you can initiate a call to return restTemplate.getForObject (" http://my-goods/goods/get", String.class) by directly using the service name. " }}
test
Elegant upper and lower line
Nacos also provides online and offline operations for service instances. On the service details page, you can click the online or offline buttons of the instance. The offline instance will no longer be obtained by the service.
Of course, as mentioned earlier, due to cache reasons, after the service is offline, the caller is not immediately aware of it and needs to wait for a certain amount of time.
So what can this feature do?
Suppose goods and services need to be upgraded
Running version: v1.0.0
Upgrade version: v1.1.0
We first deploy v1.1.0 to the production environment, where there are two instances of commodity services, v1.0.0 and v1.1.0, and then we need to take the old version offline.
If we directly stop the service, at this time the commodity service is dealing with the business, the business is interrupted, the consequences are incalculable.
If we first take v1.0.0 offline and wait for a period of time, no service will access v1.0.0 at this time, and the service can be stopped safely.
Namespace
In previous registries, one registry only corresponds to an entire micro-service system. This is because as long as services are registered to the registry, the services on the registry can access each other. As a result, each micro-service system must have its own registry, such as Eureka.
This will lead to a waste of resources, because a registry can obviously register thousands of instances (Nacos service discovery performance test report), so Nacos also provides us with the function of namespaces, which makes there is a separation mechanism between services (only services under the same namespace can access each other), so that each namespace can correspond to a micro-service system.
New Namespace
Add a new dev namespace and test namespace
Modify service configuration
Modify my-goods so that my-goods is under the dev namespace
Server: port: 8081spring: application: name: my-goods main: allow-bean-definition-overriding: true cloud: nacos: discovery: server-addr: 192.168.2.11:8850 namespace: dev username: nacos password: nacos
Modify my-order so that my-order is under the test namespace
Server: port: 8080spring: application: name: my-order main: allow-bean-definition-overriding: true cloud: nacos: discovery: server-addr: 192.168.2.11:8850 namespace: test username: nacos password: nacos
Restart the service
View the Nacos console
My-goods
My-order
test
At this time, the service is quarantined.
Thank you for your reading, the above is the content of "how to achieve the Nacos registry", after the study of this article, I believe you have a deeper understanding of how to achieve the Nacos registry, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.