当前位置:网站首页>Detailed introduction to the deployment and usage of the Nacos registry
Detailed introduction to the deployment and usage of the Nacos registry
2022-07-03 02:06:00 【Zhang weipeng】
One 、 What is a registry :
We know that microservices are deployed independently of each other 、 With clear boundaries , Services are used to build complex business functions through remote calls . The service book center plays a very important role in the micro service project , What is the registration center , What problems in microservices can be solved by using the service registry ?
1、 What is a registry :
The registry is the link in the microservice architecture , Be similar to “ Mail list ”, It records the mapping relationship between service and service address . In a distributed architecture , The service will register here , When a service needs to call another service , That's it. Find the address of the service and call it . Registry is essentially to decouple service providers and service consumers . For any micro service , In principle, there should be or support multiple providers , This is determined by the distributed nature of the microservice , Further more , In order to support the elastic expansion and contraction characteristics , The number and distribution of a micro service provider is often dynamic , It can't be determined in advance . therefore , Originally used in the monomer application phase static LB The mechanism is no longer applicable , Additional components need to be introduced to manage the registration and discovery of microservice providers , And this component is the service registry .
2、 The core function of the registry :
- Service registration : Service instance registers its service information to the registry
- Service discovery : Service instance through registry , Get information about the service instance registered in , Through this information to request the services they provide
- Service to eliminate : The service registry will automatically exclude the service in question from the available list , To prevent it from being called to
3、 Problems solved by the registry :
(1) shielding 、 Decouple the details of interdependencies between services :
Remote calls between services must know each other IP、 port . But there are obvious problems with this calling method , As called IP、 After the port changes , The caller should also synchronously modify . Discover through services , Between services IP The dependency on port is transformed into dependency on service name , The service name can be identified according to the specific micro service business .
(2) Dynamically manage services :
In the microservices architecture , There are many services and complex dependencies , Whether the service stops actively 、 Accidentally hang up , Or is the service expansion due to the increase of traffic , These dynamic changes in service status , The callee needs to be notified as soon as possible , The called party takes corresponding measures . therefore , For the service registry, the data and status of the service should be managed in real time , Including the registration and launch of services 、 The service took the initiative to go offline , Elimination of abnormal services .
(3) Reduce the pressure of load balancing middleware on the server :
When there are more and more services , service URL Configuration management becomes very difficult , Load balancing middleware on the server , such as F5、Nginx The pressure is also increasing . Through the service registry , You can dynamically register and discover services , Make the location of the service transparent , And get the address list of service provider from the consumer , Achieve soft load balancing and Failover, Reduce the load balancing middleware on the server , It can also reduce part of the cost .
4、 The implementation pattern of service discovery and registration :
above-mentioned , The hardware F5、 The software Nginx You can also realize service discovery , So what's the difference between this and service discovery in the registry ? These are actually two implementation modes of service discovery and registration : The discovery mode of the server and Client discovery mode .F5、Nginx It belongs to the discovery mode of the server , The service registry belongs to the discovery mode of the client , Both modes have their own advantages and disadvantages , It also applies to different scenarios , For large applications, there are usually multiple layers of loads , The outer layer uses server-side load balancing , Internal client load balancing . Next, let's take a look at the two service discovery modes :
(1) The discovery mode of the server :
The discovery mode of the server is through the use of an intermediate server , To shield the complexity and variability of the called service , When new services are added or old services are removed , Just modify the configuration on the intermediate server , The salient feature of this model is : Introduce an independent intermediate proxy server to shield the specific details of the real service .
As shown in the figure below : When serving A To invoke a service B when , Through the first DNS Domain name resolution found Nginx The server , Then send the request to Nginx, Because in Nginx Services are configured on B Your real access address ,Nginx After receiving the request, according to the load balancing algorithm , Forward the request to a real service B, service B Return the request result to Nginx,Nginx Then return the result to the service A, The whole request process is over . Of course, the intermediate server does not have to be Nginx, It can also be hardware based F5, It can also work on the transport layer IP Load balancing, etc. .
The advantages of this model are : The configuration is centralized on an independent intermediate server , There is no intrusion into the code , There is no cross platform and cross language problem . But the disadvantages are obvious , Because all requests need to penetrate the intermediate server , So the intermediate server will become a single point , It will also affect the performance .
(2) Client discovery mode :
Let's look at the discovery mode of the client , service A Call the service B when , No intermediate server is required , Instead, it maintains services in its own process B Information about , Then select a service through the load algorithm B Call directly . That service A Specifically, how to maintain the service B The information of ? Therefore, the concept of service registry is introduced , When serving B Register yourself with the registry at startup ( Send your information to the registry ), service A Then get all registered services from the Registration Center , This is the basic principle of client mode .
Client mode because the service is called directly in the process , Also called in-process load , Because there is no need to penetrate the intermediate server , Therefore, the performance loss of client mode is relatively small . however , You need to maintain the service registration information inside the service , Load algorithm, etc , There is a certain degree of code intrusion , For cross platform , Cross language support is not very friendly .
5、 Service registry :
In microservice Architecture , After all services are started, they register themselves through the registry , At the same time, pull the service information in the registration center back to the local , In subsequent calls, the local service and node information will be directly checked to call the service node . Each service node will come to the registry for service registration , How to save the registration information on the server , It's actually the registry , Report your information when registering the service , Then the registry puts the registry , Return to the client , Then the nodes to call the service are known between the services .
The service registry needs to be highly available and up to date . The client can cache the service address obtained from the service registry , However , This information will eventually become obsolete , The client can't find the service instance . therefore , The service registry will contain several servers , And use replication protocols to maintain consistency . The service registry cannot be a single point , Otherwise, there is a single point of failure , When there are multiple servers in the service registry, we need to consider the real-time synchronization and consistency of the service registry information on multiple machines .
Two 、 Comparison of mainstream service registries :
(1)Zookeeper and Consul follow CP principle , Strong consistency and partition fault tolerance are guaranteed , Discard availability , In a distributed environment , If the scenario involves data storage , Data consistency should be guaranteed first , But for service discovery , Usability is the core , For the same service , Even if the service provider information stored in different nodes of the registry is different , And it won't have catastrophic consequences . Because for service consumers , Consumption is the most important thing , After getting the incorrect service instance information, consumers try to consume , It is also better than system exceptions caused by failure to obtain instance information without consumption
(2)Eureka follow AP principle , Guaranteed availability , Abandon data consistency , It can basically meet the core functions required by the registration center , but Eureka 2.x Version has stopped development , And announced that if it continues to be used , Own risk .
(3)Nacos Support at the same time AP And CP, The default is AP, At the same time, it has more functions , And SpringCloud Alibaba Better compatibility with , Simpler and more flexible , It can meet more business scenarios , And support K8S Integration of .
Different service registry components have different application scenarios , Readers can choose models according to their own business conditions . But below we mainly take Nacos Take the registration center as an example , Readers of other registration centers can check online by themselves
3、 ... and 、Nacos Deployment and use of the registry :
1、Nacos Construction of Registration Center :
Let's go first Nacos Of Github(Tags · alibaba/nacos · GitHub) Download what we need Nacos edition , You can choose windows perhaps Linux, Here's the picture :
Because when building the project , Consider the relationship with SpringBoot and SpringCloud The version of the corresponding problem , I downloaded it here 2.0.0 Build the version of , Readers can choose the corresponding one according to their own situation Nacos edition .
1.1、Windows Environmental Science :
Download and unzip nacos-server-2.0.0.zip, After decompression, enter /bin Catalog , You can see the following two scripts :
windows The environment runs directly startup.cmd Start project , When the following interface appears, the startup is completed :
Type in the browser http://localhost:8848/nacos Get into Nacos Login interface of , The default user name and password are nacos, After successful login, the interface is as follows :
1.2、Linux Environmental Science :
Nacos stay Linux The start and stop of the environment follow windows The start and stop of the environment are basically the same , To download nacos-server-2.0.0.tar.zip Compressed package , And then upload it to Linux Unzip on the server ( Unpack the command :tar -zxvf nacos-server-2.0.0.tar.gz), After decompression, you can also enter /bin Execute the startup command from the directory ( Stand alone mode start command :sh startup.sh -m standalone), Visit after startup nacos Console address (http:// The server ip Address :8848/nacos/index.html) Verify whether it starts successfully .
2、SpringBoot Integrate Nacos Perform service registration discovery :
Let's take a look first nacos The simple architecture of :
Refer to the above architecture diagram , We create two modules respectively , Namely cloud-producer-server( Service providers )、cloud-consumer( Serving consumers ), The responsibilities are as follows :
- cloud-producer-server: Sign up for nacos-server, External exposure services
- cloud-consumer: Sign up for nacos-server, call cloud-producer-server Service for
Before creating these two modules , Let's first declare the version information of the project :
<properties>
<spring-boot.version>2.3.2.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
</properties>
<!-- Only declare dependencies , Do not introduce dependencies -->
<dependencyManagement>
<dependencies>
<!-- Statement springBoot edition -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Statement springCloud edition -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Statement springCloud Alibaba edition -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2.1、 Create service provider cloud-producer-server:
(1) introduce maven rely on :
<!-- Introduced to Ali nacos As a service registry -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
(2) add to nacos Related configuration information :
stay application.properties The configuration file specifies the service name 、 Port number 、nacos-server Address information for , as follows :
spring.application.name = cloud-producer-server
server.servlet.context-path = /${spring.application.name}
server.port=9000
# nacos Registry configuration
spring.cloud.nacos.discovery.server-addr = localhost:8848
spring.cloud.nacos.discovery.namespace = 91b5489b-d009-4725-86fa-534f760b4d04
spring.cloud.nacos.discovery.register-enabled = true
(3) Enable the function of service registration discovery :
In the main Application Start class join @EnableDiscoveryClient Annotations enable the function of service registration discovery , as follows :
/**
* SpringBoot Start class
* @EnableDiscoveryClient Enable the function of service registration discovery
*/
@EnableDiscoveryClient
@SpringBootApplication
public class ProducerApplication
{
public static void main(String[] args)
{
SpringApplication.run(ProducerApplication.class, args);
}
}
(4) Realize a demonstration function :
cloud-producer-server Register as a service provider to nacos in , There must be a need to provide a service for consumers cloud-consumer call , Here is a simple demo interface :
@RestController
@RequestMapping (value = "/")
public class CloudController
{
@PostMapping ("getSum")
public String getSum(@RequestParam (value = "num1") Integer num1, @RequestParam (value = "num2") Integer num2)
{
return "success: Sum result of two numbers =" + (num1 + num2);
}
}
(5) Start project :
After starting the project , We enter nacos Console , stay nacos Of “ Service management -> List of services ” Of “91b5489b-d009-4725-86fa-534f760b4d04” You will find the registered cloud-producer-server This service , Here's the picture :
2.2、 Create service consumer cloud-consumer:
The creation steps of service consumers are basically the same as those of service providers
(1) introduce maven rely on :
<!-- Introduced to Ali nacos As a service registry -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
(2) add to nacos Related configuration information :
spring.application.name = cloud-consumer
server.port=9001
# nacos Registry configuration
spring.cloud.nacos.discovery.server-addr = localhost:8848
spring.cloud.nacos.discovery.namespace = 91b5489b-d009-4725-86fa-534f760b4d04
spring.cloud.nacos.discovery.register-enabled = true
(3) Enable the function of service registration discovery :
/**
* SpringBoot Start class
* @EnableDiscoveryClient Enable the function of service registration discovery
*/
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication
{
public static void main(String[] args)
{
SpringApplication.run(ConsumerApplication.class, args);
}
}
(4) Invoke the demo function of the service provider :
cloud-producer-server The service provider provides a demonstration function , How can we call this function ? Actually Nacos Integrated Ribbon( of Ribbon Please refer to this article for a detailed introduction of :https://blog.csdn.net/a745233700/article/details/122916856), So we can use Ribbon Load balancing to invoke services , Steps are as follows :
① establish RestTemplate, Use @LoadBalanced Note that load balancing is enabled :
@Configuration
public class RestConfig
{
/**
* establish restTemplate object .
* LoadBalanced Annotation means giving restTemplate Use Ribbon The ability of load balancing ( Be sure to add notes , Otherwise, it can't be called remotely )
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
② adopt RestTemplate Request the remote service address and receive the return value
@RestController
@RequestMapping (value = "api/invoke")
public class InvokeController
{
@Autowired
private RestTemplate restTemplate;
/**
* Use RestTemplate Make a remote service call , And use Ribbon Load balancing
*/
@ApiOperation (value = "RestTemplate", notes = " Use RestTemplate Make a remote service call , And use Ribbon Load balancing ")
@GetMapping ("getByRestTemplate")
public String getByRestTemplate(Integer num1, Integer num2)
{
// first cloud-producer-server On behalf of the nacos Service name in the registry , the second cloud-producer-server representative contextPath Configured project path
String url = "http://cloud-producer-server/cloud-producer-server/getSum";
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("num1", num1);
params.add("num2", num2);
// Call the remote service through the service name ( Not ip port )
return restTemplate.postForObject(url, params, String.class);
}
}
(5) Start the test , see nacos Registration center control panel
After successful startup, it will be in nacos In the service list cloud-consumer, Here's the picture :
Then next, test whether the service can be adjusted ? Visit the... Of the service consumer api/invoke/getByRestTemplate Interface , You can see the request result as follows :
3、Nacos Cluster deployment of :
In the previous introduction , We are not interested in Nacos Do any special configuration on the server , Everything runs in the default stand-alone mode , However, the single machine operation mode is only applicable to the learning and testing environment , It is obviously not suitable for the production environment with high availability requirements . How can we build a cluster environment that supports high availability ?
In the building Nacos Before cluster , We need to modify Nacos The data persistence configuration of is MySQL Storage . By default ,Nacos Use an embedded database Derby Realize data storage , In this case , If you start multiple default configurations Nacos node , There are consistency problems with data storage . To solve this problem ,Nacos Centralized storage is adopted to support cluster deployment , But at the moment, Nacos Only support MySQL The storage , And version requirements :5.6.5+
3.1、Nacos Persistence of configuration :
(1) initialization MySQL database :
First, in the MySQL Create a new database in nacos-config( Name at will ), And then execute Nacos Medium SQL Script , The script is Nacos-server Of conf In folder nacos-mysql.sql, Here's the picture :
Execute the script , The table will be created automatically , Here's the picture :
(2) modify conf/application.properties The configuration file :
Nacos-server Also a Spring Boot project , Want to connect to your own database , Of course, you need to configure the data source , The configuration file is also in Nacos-server Medium conf Under the table of contents , Here's the picture :
Only need to application.properties Medium Mysql Configure your own data source and restart Nacos-server that will do , as follows :
# This item must be enabled , The default is commented out
spring.datasource.platform=mysql
# Be careful MySQL8.0 The above version specifies url Be sure to bring in serverTimezone Parameters
db.num=1
db.url.0=jdbc:mysql://localhost:3306/nacos_config?serverTimezone=Asia/Shanghai&characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=123456
# Optional enable configuration
nacos.cmdb.dumpTaskInterval=3600
nacos.cmdb.eventTaskInterval=10
nacos.cmdb.labelTaskInterval=300
nacos.cmdb.loadDataAtStart=false
3.2、Nacos Cluster deployment :
Nacos The official recommendation is to deploy in a cluster mode in the production environment , This avoids a single point of failure , The architecture of cluster deployment is shown below :
The request passes first Nginx The cluster forwards to Nacos In the cluster , Of course, in order to keep high availability , The database also needs to be in cluster mode . Then let's demonstrate how to build Nacos Cluster approach .
Due to conditions , We only start three on one server Nacos Service Demo .Nacos The ports of are 8848、8849、8850.
(1) Modify port number :
Nacos The default port number is 8848, So how to modify the port ? It just needs to be modified conf In the catalog application.properties Medium server.port that will do , Here's the picture :
(2) Modify cluster configuration :
So how to configure the cluster ? stay conf There is a cluster.conf.example file , Here's the picture :
Only need to cluster.conf.example Make a copy of this document as cluster.conf Put it in conf Under the table of contents , The configuration contents are as follows :
172.16.1.84:8848
172.16.1.84:8849
172.16.1.84:8850
(3) Modify the data source :
This has already been mentioned in the persistent , Only need to application.properties Replace the data source in , as follows :
# This item must be enabled , The default is commented out
spring.datasource.platform=mysql
# Be careful MySQL8.0 The above version specifies url Be sure to bring in serverTimezone Parameters
db.num=1
db.url.0=jdbc:mysql://localhost:3306/nacos_config?serverTimezone=Asia/Shanghai&characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=123456
# Optional enable configuration
nacos.cmdb.dumpTaskInterval=3600
nacos.cmdb.eventTaskInterval=10
nacos.cmdb.labelTaskInterval=300
nacos.cmdb.loadDataAtStart=false
(4) start-up Nacos:
After the above steps Nacos The cluster is already configured , start-up Nacos After success , Access to any port Nacos service , stay “ Cluster management -> The node list ” You will see the three nodes built by yourself , Here's the picture :
thus ,Nacos The cluster has been built
(5)Nginx Configuration in :
Not shown here Nginx The cluster built , Directly on the single machine Nginx Middle configuration . Directly modifying nginx Of conf file , The contents are as follows :
upstream nacos{
server 172.16.1.84:8848;
server 172.16.1.84:8849;
server 172.16.1.84:8850;
}
server{
listen 80;
location / {
proxy_pass http://nacos;
}
}
(6) Configuration in the project server-addr:
Now that the cluster has been built , Then the project should also be configured , There are two ways , Here are the introduction :
The first one is : Configure through direct connection , as follows :
spring:
application:
## Specify the service name , stay nacos The name of
name: cloud-producer-server
cloud:
nacos:
discovery:
# nacos Service address of ,nacos-server in IP Address : Port number
server-addr: 172.16.1.84:8848,172.16.1.84:8849,172.16.1.84:8850
The second kind : Direct connection Nginx, as follows :
spring:
application:
## Specify the service name , stay nacos The name of
name: cloud-producer-server
cloud:
nacos:
discovery:
# nacos Service address of ,nacos-server in IP Address : Port number
server-addr: 172.16.1.84:80
Nacos Cluster construction is very simple , The only configuration is in cluster.conf Set three in Nacos Address of service .
Reference article :
Why should microservices have service discovery and registration ?
Fifty five pictures show you the soul ferry of micro service Nacos How strong ?
边栏推荐
- [fluent] hero animation (hero animation use process | create hero animation core components | create source page | create destination page | page Jump)
- 树形结构数据的处理
- A 30-year-old software tester, who has been unemployed for 4 months, is confused and doesn't know what to do?
- [camera special topic] Hal layer - brief analysis of addchannel and startchannel
- "Jetpack - livedata parsing"
- [shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)
- Groovy, "try with resources" construction alternative
- Network security - talking about security threats
- DML Foundation
- Cfdiv2 Fixed Point Guessing - (2 points for Interval answer)
猜你喜欢
The testing process that software testers should know
Stm32f407 ------- IIC communication protocol
LabVIEW安装第三方VISA软件后NI VISA失效
How do it students find short-term internships? Which is better, short-term internship or long-term internship?
小程序开发的部分功能
In the face of difficult SQL requirements, HQL is not afraid
Wechat applet development tool post net:: err_ PROXY_ CONNECTION_ Failed agent problem
查询商品案例-页面渲染数据
全链路数字化转型下,零售企业如何打开第二增长曲线
[fluent] hero animation (hero animation use process | create hero animation core components | create source page | create destination page | page Jump)
随机推荐
Network security - firewall
Network security - virus
Iptables layer 4 forwarding
树形结构数据的处理
Technology sharing | Frida's powerful ability to realize hook functions
The testing process that software testers should know
创建+注册 子应用_定义路由,全局路由与子路由
Caused by: com. fasterxml. jackson. databind. exc.MismatchedInputException: Cannot construct instance o
《上市风云》荐书——唯勇气最可贵
Asian Games countdown! AI target detection helps host the Asian Games!
Leetcode 183 Customers who never order (2022.07.02)
Hard core observation 547 large neural network may be beginning to become aware?
Stm32f407 ------- IIC communication protocol
函数的定义和调用、this、严格模式、高阶函数、闭包、递归
Performance test | script template sorting, tool sorting and result analysis
Method of removing webpage scroll bar and inner and outer margins
[camera topic] how to save OTP data in user-defined nodes
去除网页滚动条方法以及内外边距
[error record] navigator operation requested with a context that does not include a naviga
Trial setup and use of idea GoLand development tool