Hello everyone, I am xiao CAI, a desire to do CAI Not CAI xiao CAI in the Internet industry. Soft but just, soft praise, white piao just! Ghost ~ remember to give me a three – even oh!
This article mainly introduces Nacos in microservices
Refer to it if necessary
If it is helpful, do not forget the Sunday
Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!
Before we talk about Nacos, we need to know what Nacos is: Nacos is an open source product of Alibaba. It is a comprehensive solution for service discovery, configuration management and service governance in microservices architecture.
Answer from the official website:
Nacos is dedicated to helping you discover, configure, and manage microservices. Nacos provides an easy-to-use feature set to help you implement dynamic service discovery, service configuration management, and service and traffic management. Nacos helps you build, deliver, and manage microservices platforms more agile and easily. Nacos is the service infrastructure for building modern “service” centric application architectures (e.g., microservices paradigm, cloud native paradigm).
To sum up, four characteristics of Nacos are obtained:
- Service discovery and service health check
- Dynamic configuration Management
- Dynamic DNS Service
- Service and metadata management
The appended drawings:
It’s amazing to see how much of the mainstream open source ecosystem Nacos supports!
First, the entry base operation
use
Nacos is also extremely simple to use. Here is how to install Nacos on Windows
Step 1
Click the download address to download the latest stable version
Step 2
Double-click startup. CMD in the bin directory to start the server
Step 3
Through the browser to http://127.0.0.1:8848/nacos open nacos console login page, the default user name password is: nacos, after the success of the login to access the main page.
Extended use
Release configuration
We can release configuration by means of address: http://127.0.0.1:8848/nacos/v1/cs/configs, using the postman for testing:
Access to the configuration
We can obtain configuration by means of address: http://127.0.0.1:8848/nacos/v1/cs/configs, using the postman for testing:
Publishing service
We can address for service registration: http://127.0.0.1:8848/nacos/v1/ns/instance, using the postman for testing:
Service discovery
We can address the discovery service: http://127.0.0.1:8848/nacos/v1/ns/instance/list,
Test using Postman:
External database support
By default, nacOS uses an embedded database for data storage. If we want to use external mysql to store NACOS data, perform the following steps:
- Step 1
Install Mysql (between 5.6.5 and 8)
- Step 2
Initialize mysql database, create database nacOS, and load conf/nacos-mysql.sql
- Step 3
Modify the conf/application. The properties file, add the mysql data source configuration, and then restart, can take effect
2. Configuration management
We already know that one of Nacos’s features is for configuration centers. Configuration center is in microservice architecture, when the system is split from a single application into individual service nodes on a distributed system, the configuration file must be split along with the migration, so that the configuration is scattered, and there are redundant parts of each configuration.
Roles of the configuration center:
The configuration center separates configurations from applications and manages configurations in a unified manner. Applications do not need to manage configurations themselves
From the figure, we can summarize the process as follows:
- Users update configuration information in the configuration center
- Service A and service B receive configuration update notifications in A timely manner and obtain updates from the configuration center
Release configuration
- In Step 1, you can create namespaces. Namespaces are used to isolate multiple environments (such as development, test, and production), and each application has different values for the same configuration (such as database configuration) in different environments.
- In Step 2, we can switch between different namespaces to publish different configurations. A UUID like string under the namespace is the unique ID of each namespace.
- In Step 3, we can click Publish configuration, where DataId and Group are mandatory
After completing the above three steps, we can see that a newly configured message is generated
Access to the configuration
We can then read the configuration in the project as follows:
- Step 1
Introduce nacOS-client package in POM file:
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>1.1.3</version>
</dependency>
Copy the code
- Step 2
Using the API provided under the nacos-Client package to obtain the configuration:
public static void main(String[] args) throws NacosException {
// Use the nacOS client to remotely obtain the configuration information on the NACOS service
/ / nacos server address
String serverAddr = "127.0.0.1:8848";
//data id
String dataId = "application-dev.properties";
//group
String group = "DEFAULT_GROUP";
//namespace
String namespace = "dfa1c276-69f7-47d6-9903-6850b9c248f7";
Properties properties =new Properties();
properties.put("serverAddr",serverAddr);
properties.put("namespace",namespace);
// Get the configuration
ConfigService configService = NacosFactory.createConfigService(properties);
// String dataId, String group, long timeoutMs
String config = configService.getConfig(dataId, group, 5000);
System.out.println(config);
}
/* OUTPUT:
spring.datasource.mysql.driverClassName = com.mysql.cj.jdbc.Driver
*/
Copy the code
The configured management model is shown in the figure below:
- NameSpace (NameSpace)
Namespaces are used for configuration isolation in different environments (development, test, and production). You can have configuration groups or configuration sets with the same name in different namespaces.
- Configuring Groups
A configuration group is used to group configuration sets. Different configuration groups can have the same configuration set (DateId). The default configuration group name is DEFAULT_GROUP. Used to distinguish between different projects or applications.
- Configuration Set (DataId)
In the system, a configuration file is usually a configuration set. A configuration set can contain various configuration information of the system. For example, a configuration set may contain configuration items such as data sources, thread pools, and log levels. Each configuration set can define a meaningful name.
Distributed configuration
Before we look at centrally managing the configuration of multiple services through Nacos, let’s look at the following concepts:
Traditional monomer architecture
All function modules are packaged together and run in a Web container, all using the same database.
Features:
- High development efficiency
- Easy to test
- Easy to deploy
Disadvantages:
- Complexity gets higher and maintainability gets worse
- Version iterations gradually slow down
- Impeding technological innovation
- Cannot scale on demand
Microservices Architecture
Microservices are simply the splitting of a project into multiple services. Each microservice is a complete application, with its own business logic and database. Each business module is completed with an independent service. This microservice architecture model also affects the relationship between the application and the database. Unlike the traditional multiple business modules sharing a database, each microservice plus has its own database.
Advantages:
- Divide and rule, single duty
- scalable
- Parts are easy to modify, replace and deploy, which is conducive to continuous integration and rapid iteration
- Not tied to any technology stack
Nacos
Without further ado, let’s go straight to code to demonstrate the use of the configuration center:
- Step 1 – Publish the configuration
We create two profiles on the Nacos home page:
Service_a. Properties:
Service_b. Properties:
- Step 2 – Create the parent project
Pom. XML is as follows:
- Step 3 – Create a submodule
service-a
Pom. XML is as follows:
The bootstrap. Yml as follows:
- Step 4 – Create submodules
service-b
Pom. XML is as follows:
The bootstrap. Yml as follows:
The project directory structure is as follows:
ConfigController is as follows:
The result of service-a is as follows:
The result of service-b is as follows:
You can see that the above steps successfully obtained the contents of the configuration file we created in NACOS. The key steps we need to pay attention to are as follows: 1. Introduce jar packages of Spring-cloud-alibaba-dependencies and Spring-cloud-starter-Alibaba-nacos-config. 2. The configuration file we created under Resources must be bootstrap and not application 3
Is bootstrap. yML up to something?
We saw above that the configuration core point is:
spring:
application:
name: service_a
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848 Configure the center address
# spring.application.name + file-extension = service_a.properties
file-extension: properties # dataid The suffix of the name
namespace: dfa1c276-69f7-47d6-9903-6850b9c248f7 Specify a specific namespace
group: TEST_GROUP
Copy the code
We all know that development requires high cohesion and low coupling. If we have the same configuration item, we can extract it into a single file, so we have to import multiple configuration files. Of course, nacOS also supports the configuration as follows:
spring:
application:
name: service_a
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848 Configure the center address
# spring.application.name + file-extension = service_a.properties
file-extension: properties # dataid The suffix of the name
namespace: dfa1c276-69f7-47d6-9903-6850b9c248f7 Specify a specific namespace
group: TEST_GROUP
# ext-config
ext-config[0]:
data-id: service-common_1.properties
ext-config[1]:
data-id: service-common_2.properties
group: GLOBALE_GROUP
ext-config[2]:
data-id: service-common_3.properties
group: REFRESH_GROUP
refresh: true # Dynamic refresh configuration
Copy the code
Note that ext-config starts at 0, and the refresh TAB is used for dynamic refresh, meaning that the project can read the latest configuration file in real time without restarting it.
You may feel that ext-config is a bit cumbersome and requires so much writing. For simplicity we can also use shared-dataids and refreshable-dataids to implement the same functions as above, as follows:
spring:
application:
name: service_a
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848 Configure the center address
# spring.application.name + file-extension = service_a.properties
file-extension: properties # dataid The suffix of the name
namespace: dfa1c276-69f7-47d6-9903-6850b9c248f7 Specify a specific namespace
group: TEST_GROUP
shared-dataids: service-common_1.properties,service-common_2.properties,service-common_3.properties
refreshable-dataids: service-common_3.properties
Copy the code
Shared-dataids support the configuration of multiple shared Data ids separated by commas. Use refreshable-dataids to support the Data ids of shared configurations. Whether the application can refresh dynamically when the configuration changes and be aware of the latest configuration value. Multiple Data ids are separated by commas. If no Data Id is specified, all Data ids configured for the share do not support dynamic refreshing by default.
Set the priority of the item
Way # 1
file-extension: properties # dataid The suffix of the name
namespace: dfa1c276-69f7-47d6-9903-6850b9c248f7 Specify a specific namespace
group: TEST_GROUP
Way # 2
ext-config[0]:
data-id: service-common_1.properties
ext-config[1]:
data-id: service-common_2.properties
group: GLOBALE_GROUP
ext-config[2]:
data-id: service-common_3.properties
group: REFRESH_GROUP
refresh: true # Dynamic refresh configuration
Way # 3
shared-dataids: service-common_1.properties,service-common_2.properties,service-common_3.properties
refreshable-dataids: service-common_3.properties
Copy the code
We have learned that nacOS can be configured in three ways, among which priority is:
Mode 1 > Mode 2 (internal comparison: a larger n indicates a higher priority) > Mode 3
Now that we’ve seen the use of Nacos as a configuration center, let’s take a look at Nacos as a registry for services!
3. Service discovery
What is service discovery
In the microservices architecture, the entire system is divided into multiple services according to their responsibilities, and business goals are achieved through inter-service interaction. In order to complete the request, the consumer needs to know the network location (IP address and port number) of the service producer
Service discovery Center comparison
Compare the project | Nacos | Eureka | Consul | ZooKeeper |
---|---|---|---|---|
Consistency protocol | AP and CP models are supported | AP model | CP model | CP model |
Health check | TCP/HTTP/MYSQL/Client Beat | Client Beat | TCP/HTTP/gRPC/Cmd | Keep Alive |
Load balancer | Weight/metadate/Selector | Ribbon | Fabio | – |
Avalanche protection | There are | There are | There is no | There is no |
Automatic logout instance | support | support | Does not support | support |
Access protocol | HTTP/DNS | HTTP | HTTP/DNS | TCP |
Listening to the support | support | support | support | support |
Multi-data center | support | support | support | Does not support |
Synchronization across registries | support | Does not support | support | Does not support |
SpringCloud integration | support | support | support | Does not support |
Dubbo integration | support | Does not support | Does not support | support |
K8s integration | support | Does not support | support | Does not support |
Introduction to Service Discovery
Practice is better than words, let’s not say much, directly on the code:
- Step 1 – Create a parent project
Pom. XML is as follows:
- Step 2 – Create a service producer
Pom. XML is as follows:
Application. Yml as follows:
The startup classes are as follows:
ProviderController. Java is as follows:
This is the generator’s code. The key points are: 1. Introduce the Spring-cloud-starter-Alibaba-nacos-discovery JAR package 2. In the startup class annotation @enableDiscoveryClient annotation 3. Configure the address of nacOS service center in application.yml 4. Expose the service in controller
- Step 3 – Create a service consumer
Pom. XML is as follows:
Application. Yml as follows:
The startup classes are as follows:
ConsumerController. Java is as follows:
The above is the code for the consumer, where the key points are: 1. Introduce the Spring-cloud-starter-Alibaba-nacos-Discovery JAR package 2. In the startup class annotation @enableDiscoveryClient annotation 3. Configure the address of nacOS service center in application.yml 4. Use the RestTemplate in the Controller to invoke the service.
We can see that there are two services registered in Nacos, service-provider and service-consumer, which we can also see on the Nacos console:
Similarly, service registration also supports namespace isolation. We simply add the configuration in application.yml:
server:
port: 8083
spring:
application:
name: service-consumer
cloud:
nacos:
discovery:
server-addr: 127.0. 01.: 8848
# namespaces
namespace: dfa1c276-69f7-47d6-9903-6850b9c248f7
cluster-name: DEFAULT
Copy the code
The use of Feign
Feign is a declarative, template-based HTTP client developed by Netflix to help us invoke HTTP apis quickly and elegantly.
Feign is also very simple to use in the following steps:
- Step 1
Declare Feign client:
@FeignClient(value = "service-provider") // Producer name
public interface ConsumerService {
@GetMapping("/getData")
String getDate(a);
}
Copy the code
- Step 2
Add the @enableFeignClients annotation to the startup class
- Step 3
Call from the Controller layer:
@RestController
public class ConsumerController {
@Autowired
private ConsumerService consumerService;
@GetMapping("/getData")
public String getData(a) {
String date = consumerService.getDate();
return "consumer consumer ---"+ date; }}Copy the code
Results:
Simple use, reduce irrelevant HTTP request related code, make business logic clear.
END
This is the introduction of Nacos in microservices, and I hope to see you learn something from it! The road is long, small dishes with you to seek ~
Today you work harder, tomorrow you will be able to say less words!
I am xiao CAI, a man who studies with you. 💋
Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!