The following questions will be examined:
- Nacos’s Role: How does Nacos work? What is the role in the cluster?
- Modify the NACOS configuration database: The information we configure in the console is written to the nacOS default database by default, which is not easy to manage, so we set up a database of our own to manage operations
- Configure the NACOS configuration on the console
- Nacos configuration management model: basic concepts,namespace, group, data ID and usage
- Manage namespace and use namespace
- Nacos configuration management is applied to distributed systems
- 7.Nacos cluster deployment
The role of Nacos
This diagram shows that nacOS is a separate server, and that users change or publish configuration information to notify downstream servers. The downstream server can also read the configuration information of the configuration center according to certain rules.
Make NACOS part of the Spring Cloud cluster
-
Start the NacOS service
-
Nacos as part of spring Cloud microservices
-
Register other Spring Cloud application services with nacOS.
Modify the NACOS configuration database
Let’s verify the availability of the service
1. Start the nacos
./startup.sh -m standalone
Note: we must start in single-machine mode, the default is cluster mode, we are not in the cluster, will report an exception.
2 Publish the configuration to the configuration center
Nacos is a service that also provides a number of interfaces, including one for adding configurations. We simulate this interface for configuration:
curl -X POST “http://localhost:8848/nacos/v1/cs/configs? dataId=nacos.cfg.dataId&group=test&content=HelloWorld”
See that the return result is true. Then refresh the console and see the following
3. Obtain the configuration from the configuration center
curl -X GET “http://localhost:8848/nacos/v1/cs/configs? dataId=nacos.cfg.dataId&group=test”
This command is to get the configuration
Get the HelloWorld content
4. Change the storage location of nacOS configuration data
We add configuration information to nacOS, so how does it save? Nacos A default built-in database that is not easy to operate and find. So we replaced it with our own mysql database
1. Prepare a mysql database
Because mysql is quite large, I use mysql installed by Docker
Download mysql
Docker pull mysql: 5.7.15
Start the mysql
docker run -p 3306:3306 –name MySQLDocker -v The PWD/conf/my. CNF: / etc/mysql/conf. D/my CNF – vPWD/conf/my CNF: / etc/mysql/conf. D/my. CNF – v The PWD/conf/my. CNF: / etc/mysql/conf. D/my CNF – vPWD/logs: / var/log/mysql – v $PWD/data: / var/lib/mysql – e MYSQL_ROOT_PASSWORD = 123456 – d mysql: 5.7.15
2. Create a nacOS_config database
3. Initialize the nacOS_config table structure
Find the configuration file here: ${nacosHome}/conf/nacos-mysql.
4. Modify the application.properties configuration file Then restart.
Perform the write configuration above
A configuration message is generated in the database:
3. Nacos configuration
1. Add the configuration on the console
Data ID: nacos-simple-demo.yaml Group: DEFAULT_GROUP Configuration format: YAML Configuration content: common config: somethingCopy the code
The above information is configured on the consoleThis is the configuration information set up on the NACOS server
2. Simulate the NACOS client — get the NACOS server configuration
public class DemoTest { public static void main(String[] args) throws NacosException { String dataId = "test.demo.yml"; String group = "DEFAULT_GROUP"; String serverAddr = "localhost:8848"; Properties properties = new Properties(); properties.setProperty("serverAddr", serverAddr); / / and nacos services linking the ConfigService ConfigService. = NacosFactory createConfigService (properties); String config = configService.getConfig(dataId, group, 10); System.out.println(config); }}Copy the code
Ok, and you can get the configuration information for NACOS
4. Model of NACOS configuration management
For NACOS configuration management, namespace, Group, dataId can be used to locate a configuration set.
Nacos configuration management model consists of three parts: namespace, Group, service/data Id. Through the configuration management model, we can locate the required configuration files
In service/data Id, server is for service discovery and dataId is for configuration management.
1. Configuration set (DataId)
The configuration set is the DataId shown above
In a system, a configuration file is usually a configuration set. A configuration set can contain various configuration information for a system. For example, a configuration set may contain configuration information about the system data source, connection pool, and log level. Each configuration set can have a meaningful name, which is the Id of the configuration set, that is, the Data Id
2. Configuration items
Each configuration item in a configuration set is a configuration item. It represents specific configurable parameters. Usually in the form of key=value.
3. Configure groups.
Configuration groups are groups in the figure above. Configuration groups are groups of configuration sets. Represented by a meaningful string such as buy, trade. Different configuration groups can have the same configuration set (Data ID). When you create a configuration on nacOS, if you do not specify a configuration group name, the default name DEFAULT_GROUP is used.
Common scenarios for configuring groups are as follows: Groups are used to distinguish different projects or applications. For example, in the student management system configuration set, you can define a group as STUDENT_GROUP.
4 Namespace (Namespace)
Namespaces can be used to configure isolation of different environments. For example, you can isolate the development environment, test environment, and build environment. Because their configurations may vary. Or you can isolate different users, where different developers use the same nacOS to manage their configuration and can be isolated through a namespace. A configuration Group or Data Id with the same name can exist in different namespaces.
Best practice we can usually define namespace, group, datAID as follows
-
Namespace: Represents different environments, such as development, test, production, etc
-
Group: can represent a certain project, such as XX medical project and XX e-commerce project
-
DataId: There are usually several projects under each project, and each configuration set (DataId) is the master configuration file of a project
Analyze with existing projects
5. Namespace management
Let’s review the client implementation above. In the client implementation above, we did not define a namespace. Then it will use the default namespace public.
1. Isolation design of namespace
- Design namespaces for the environment: development, testing, production
The configurations of such different environments are isolated from each other and do not affect each other
- It can also be designed in a multi-user fashion. For example, Zhang SAN, Li Si, Wang Wu, they see their own content is different.
2. Manage namespaces
Creating a namespace
Interface operation is relatively simple, not all said
Now I’ve created four namespaces. Where public and dev both have a Data Id called test.demo.yml. I’m going to get the test.demo.yml configuration file under dev through the program code.
The simulation client obtains the configuration information under the namespace dev of nacOS:
package com.lxl.org;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import java.util.Properties;
public class DemoTest {
public static void main(String[] args) throws NacosException, InterruptedException {
String dataId = "test.demo.yml";
// 注意: 这里填的是命名空间的id
String namespace = "dev";
String group = "DEFAULT_GROUP";
String serverAddr = "localhost:8848";
Properties properties = new Properties();
properties.setProperty("serverAddr", serverAddr);
properties.setProperty("namespace", namespace);
// 和nacos服务建立连接
ConfigService configService = NacosFactory.createConfigService(properties);
String config = configService.getConfig(dataId, group, 10);
System.out.println(config);
Thread.sleep(1000);
}
}
Copy the code
You need to specify under which namespace to get the configuration.
3. View historical versions
The historical version here is a point that can be rolled back. Click rollback to roll back to a version of the configuration
4. Listen to queries
Want to listen for a configuration file in the development environment. Let’s look at the listening query to see which configuration files are being listened on.
For example, let’s write a demo and listen to the test.demo.yaml configuration file under dev
public static void main(String[] args) throws NacosException, InterruptedException { String dataId = "test.demo.yml"; String Namespace = "a127e7f7-e37e-48FB-9968-cca7ef7c9f26 "; String Namespace =" a127e7f7-e37e-48Fb-9968-cca7ef7c9f26 "; String group = "DEFAULT_GROUP"; String serverAddr = "localhost:8848"; Properties properties = new Properties(); properties.setProperty("serverAddr", serverAddr); properties.setProperty("namespace", namespace); / / and nacos services linking the ConfigService ConfigService. = NacosFactory createConfigService (properties); String config = configService.getConfig(dataId, group, 10); System.out.println(config); configService.addListener(dataId, group, new Listener() { @Override public Executor getExecutor() { return null; } @override public void receiveConfigInfo(String s) {system.out.println (s); }}); Thread.sleep(1000000); }Copy the code
Write a listener and keep listening. As soon as any configuration changes, you can be notified.
5. Login management
Nacos supports a simple login function. The default user name/password is nacos/nacos.
You can change the default user name and password as follows:
By looking at the source code can know that nacOS user encryption is the use of BCrypt encryption. Therefore, we can simulate a BCrypt method to change the password
- Introduce the BCrypt JAR package into the project
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> < version > 5.1.4 ensuring. RELEASE < / version > < / dependency >Copy the code
Then write a method to change the password
package com.lxl.org; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class PasswordHandler { public static void main(String[] args) { String encode = new BCryptPasswordEncoder().encode("123"); System.out.println(encode); }}Copy the code
Replace the password in the database
$2a$10$LW/6RKgceuALErDPcU8THOT5V1Ajc98jgo6N38oOX0Tvmce39hP4a
Copy the code
You need to set the user name and role for a new user
insert into users(username, password, enabled) VALUES ("lxl", "$2a$10$LW/6RKgceuALErDPcU8THOT5V1Ajc98jgo6N38oOX0Tvmce39hP4a", 1);
insert into roles(username, role) VALUES ('lxl', 'ROLE_ADMIN')
Copy the code
It can also be modified at the console
Vi. Nacos configuration management for distributed systems
The following figure shows how NACOS centrally manages multiple configuration services
-
Users centrally manage configuration files through the console of the NacOS service
-
Each service gets its own configuration from NACOS and listens for configuration changes.
1. Simulate a scenario where two microservices request a registry.
1. In the dev environment, create two configuration files: server1 and server2
2. Create a simple microservice architecture. Spring Cloud microservices architecture is adopted. Create a parent project to introduce common configurations. Before creating two microservices server1, server2 create a parent Maven project and import the Maven package
<dependencyManagement> <dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> < artifactId > spring - the cloud - alibaba - dependencies < / artifactId > < version > 2.1.0. RELEASE < / version > < type > pom < type > <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Greenwich.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> < artifactId > spring - the boot - dependencies < / artifactId > < version > 2.1.3. RELEASE < / version > < type > pom < type > <scope>import</scope> </dependency> </dependencies> </dependencyManagement>Copy the code
Create a service1. Then add maven management for NacOS. After adding the bootstrap.yml configuration file, finally add the bootstrap.yml class
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Copy the code
Configuration file bootstrap.yml. Note that the default data Id to look for is the application plane + extension
server: port: 56010 spring: application: name: service1 cloud: nacos: config: server-addr: Localhost :8848 file-extension: yaml namespace: dev group: TEST_GROUP # Default data Id --> application name + file extension -->service1.yamlCopy the code
Finally, add the startup class, which defines a controller directly to get configuration information
package com.lxl.www.service1; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class BootStrapApplication { public static void main(String[] args) { SpringApplication.run(BootStrapApplication.class, args); } @value ("${common.config}") private String config1; /** * Define a controller */ @getMapping (value = "/config") public String getNacosConfig() {return config1; }}Copy the code
The same goes for service2.
Note: When publishing nacOS, open the log file to see if the publishing was successful. If an exception is reported, the publication may fail. Description The project failed to obtain the configuration fileCopy the code
The client here uses the NacOS client provided by Ali: Spring-Cloud-starter – Alibaba – Nacos-config
Existing problems:
When we use spring’s @value annotation, we find that the content of the configuration file has been modified in the configuration center, but the content read through the annotation remains the same. What’s the fuss? In fact, when the configuration file changes, it notifies the server. The reason it does not change is because of the @value attribute. It must have cache. If you want to dynamically obtain the modified configuration file, there are two ways:
Method 1: Use Properties.
The method of obtaining the configuration is modified as follows:
@Autowired private ConfigurableApplicationContext applicationContext; /** * Define a controller */ @getMapping (value = "/config") public String getNacosConfig() {return applicationContext.getEnvironment().getProperty("common.config"); }Copy the code
Method 2: @nacosValue
Matters needing attention:
- The configuration information of nacOS is written in bootstrap.yml. Bootstrap. yml is loaded earlier than application.yml.
2. Extend DataId, multi-configuration processing
If there are more than one configuration file, we can use extended configuration to add more configuration files
Ext-config [0]: data-id: ext-config-common01. Yml ext-config[1]: data-id: ext-config-common01 ext-config-common02.yml group: GLOBAL_GROUP ext-config[2]: data-id: ext-config-common03.yml group: Refresh: trueCopy the code
In the first configuration, there is only one data-id. There is no group, and the default DEFAULT_GROUP is used.
Second extension configuration. Defines a GLOBAL_GROUP. Global configuration
Third extension configuration: define as an auto-refresh GROUP and set the auto-refresh property to true next we add these three files to the console
Modifying an interface to obtain configuration information
/** * Define a controller */ @getMapping (value = "/config") public String getNacosConfig() {String p1 = applicationContext.getEnvironment().getProperty("common.config"); String p2 = applicationContext.getEnvironment().getProperty("common.ext1"); String p3 = applicationContext.getEnvironment().getProperty("common.ext2"); String p4 = applicationContext.getEnvironment().getProperty("common.ext3"); return p1 + "+" + p2 + "+" + p3 + "+" + p4; }Copy the code
We can see what it looks like in print
When we modify the configuration file in the console, we find that common.config changes. Common.ext3 changes. The other two are not automatically updated
Summary: The default configuration can be refreshed automatically. In the extended configuration, the refresh will only happen automatically if the attribute refresh:true is added
3. Share the Data Id
We can set the shared data ID as follows:
Set the shared data ID. We set three files. Start the project and the result is as follows
We find that two of them are null. If you want to configure multiple extension files, you also need to extend dataId because only the first file takes effect in this way.
4. Set the priority of the Data Id
There are three ways to set a Data Id
- Default data ID. Project name + extension method.
- Use ext-config[0] to set the extension configuration
- Using shared-dataids: Set up the shared configuration.
So what are their priorities?
Default configuration > ext-config > shared-dataids If there are more than one ext-Config extension configuration, which one has the higher priority? A larger number of n indicates a higher priority…..
ext-config[n] > ext-config[2] > ext-config[1] > ext-config[0]
5. Disable the Nacos configuration
If you do not want to use nacOS configuration, you can set the enable attribute to false
7. Nacos cluster deployment
Usually we can’t have just one NACOS in a build environment. To ensure high availability, we configure multiple nacOs.
Requirements: Configure three or more nacOS services
Let’s simulate three NACOS service clusters
Step 1: Unpack the three NACOS services
Step 2: Modify the configuration file
- Change the port number to 8848, 8849, and 8850 respectively
2. Add the IP address of the local service
Add the following configuration to all three services: Set the local IP address
Nacos. Inetutils. IP address = 127.0.0.1
3. Set the cluster relationship among the three nacOs
Example change the cluster.conf.example file to cluster.conf
And add the following to it
Step 4: Start three servers. Start in cluster mode./start.sh -m cluster then, in control he looks at the cluster, there is one master and two slave
Step 5 Configure the NACOS cluster in the project
Note: Multiple configurations cannot be separated by Spaces.
Restart the project. Access interface returns content
In this case, we can disable any nacOS service. As long as there is one running, the service can be accessed