Cloud-Nacos installation, registration and configuration center

Starting from this article is to start the journey of Spring Cloud. In fact, Spring Cloud is not complicated. It is composed of various components. It can also be said that it integrates various components. You can also choose to use the same type of components, such as zk, eureka, consul, nacos, etc. in the registration center. These can be composed The registration center component of the cloud system, but due to various reasons, and the elimination of technology selection, the solutions used by each enterprise are also different, and some large enterprises use self-developed components, but these will eventually be replaced. cloud integrated use.

At present, the most commonly used is a set of component solutions provided by Ali: microservice gateway-getway, service call-openFeign, registration and configuration center-nacos, current limiting and downgrading-sentinel, distributed transaction management-seata, these five major components A distributed microservice system is built. Of course, a complete project must have other middleware besides these, such as: skywalking for link tracking, Redis for caching, xxl-job for platform task scheduling, etc.

Installation and use of nacos

The above introduction also said that there are many options for registration and configuration centers of the cloud system, but nacos is the most commonly used in the market at present, or a self-developed middleware can be layered on top of nacos.

Speaking of nacos itself, nacos can be said to be very easy to learn. The reason is very simple. It belongs to Ali. In other words, its documents and the content shared by the community are basically in Chinese. There are docker, cloud, boot, etc. in the official documents. Instructions for combined use in various aspects, and an excellent visual view itself, which is easy to use and easy to operate.

Here is a word, because the cloud project is a whole, so when learning a single component, other components will inevitably be involved, but don't get too entangled in the use of other components, just focus on the content of the current single component.

nacos overview

Before the official start, it is still necessary to briefly copy the overview and basic concepts of the official website.

nacos is a dynamic service discovery, configuration management, and service management platform that is easier to build cloud-native applications. It provides a set of easy-to-use feature sets that can quickly realize dynamic service discovery, service configuration, service metadata, and traffic management.

There are many concepts in nacos. Those who are interested can go to the official website to learn more, but there are a few basic concepts that must be understood:

  1. Namespace : This is the key point. Namespace is also the command space, which is used for tenant granular configuration isolation. In the case of no configuration, nacos only provides a command space named public. If you want to distinguish and isolate the configuration of different environments, you must configure it yourself.
  2. Service Registry : A database that stores service instances and service load balancing policies.
  3. Configuration management : all configuration-related activities such as system configuration editing, storage, distribution, change management, historical version management, and change auditing.
  4. Instance: A process with an accessible network address (IP:Port) that provides one or more services.
  5. Weight: Configuration at the instance level. Weights are floats. The greater the weight, the greater the traffic allocated to the instance.
  6. Health check: provided by nacos to check the runtime status of the registration service.

Among the many concepts, the most important ones are the first three above. Namespace command space is the foundation of everything. nacos itself also provides a basic public command space, and this command space cannot be deleted; service registration center , service registration and discovery are all done on this basis; similarly, configuration management is the configuration center of the project, and this module stores all registered configuration information.

nacos also has some configurations such as roles and permissions, which can be used for isolation management of projects, etc., which will be demonstrated bit by bit later.

The docker installation process of nacos

Because docker itself needs to do configuration management and authority management, it needs data persistence, so it needs to use a database. Generally speaking, if you use nacos, you choose mysql as the plug-in for data persistence, but this will also lead to direct installation. It is troublesome, and it takes up a lot of memory, and it is not very convenient to start. We can install and use it in combination with docker. For personal learning, there is no need to install a large k8, just use docker-compose to arrange it.

I won’t talk about the installation and use of docker and docker-compose here. If you haven’t touched this kind of knowledge for the time being, you can read my previous article about docker first, or you can skip this installation content and go directly to the combination project. use content.

After docker and docker-compose are installed, you can download a tar.gz package of the corresponding version from the official website of nacos. I downloaded version 2.2.1 , and you can see it by pulling down the access link at the bottom.

image-20230413175724959

After downloading, decompress to get a nacos-docker version file. In the example folder, there are docker-compose files about nacos single-point and cluster startup. Let's find a single-point startup file combined with mysql to analyze.

The following is the standalone-mysql-8.yaml file

version: "3.8"
services:
  nacos:
    image: nacos/nacos-server:${
    
    NACOS_VERSION}
    container_name: nacos-standalone-mysql
    env_file:
      - ../env/nacos-standlone-mysql.env
    volumes:
      - ./standalone-logs/:/home/nacos/logs
    ports:
      - "8848:8848"
      - "9848:9848"
    depends_on:
      mysql:
        condition: service_healthy
    restart: always
  mysql:
    container_name: mysql
    build:
      context: .
      dockerfile: ./image/mysql/8/Dockerfile
    image: example/mysql:8.0.30
    env_file:
      - ../env/mysql.env
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3306:3306"
    healthcheck:
      test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
      interval: 5s
      timeout: 10s

Parse:

  1. version: docker-compose version 3.8.
  2. services: two services under the hierarchy, nacos and mysql.
  3. image: The imported image.
  4. container_name: service name.
  5. build: build the image, context: build the image in the current directory, dockerfile: the location of the Dockerfile.
  6. env_file: The file location of the configuration information.
  7. volumes: The location of the bind mount files.
  8. ports: The set of exposed ports. It should be noted that nacos must expose 9848 of the container, because the gRpc request of nacos version after 2.0 will offset the port.
  9. healthcheck: script configuration.
  10. restart: Start policy.
  11. depends_on: This is the missing content in the previous docker article, which means waiting for the corresponding service to start first. For example, here is to start mysql first, and then start nacos after passing the health check. The condition stipulates that the version above 3.2 can be used. It has three attributes.
    service_started: indicates that the service is started after the dependent service is started;
    service_healthy: indicates that the service is started after the dependent service passes the health check;
    service_completed_successfully: Indicates that the service will not be started until the dependent service is successfully executed.

The content of the above docker-compose is still relatively complicated, and it must be used in a specified directory. I have changed a version here, and it can be used in any directory, but the premise is to follow my path and place the nacos-docker file decompressed above. .

version: "3.8"
services:
  nacos:
    image: nacos/nacos-server:v2.2.0
    container_name: nacos
    env_file:
      - /app/nacos/nacos-docker/env/nacos-standlone-mysql.env
    volumes:
      - /app/nacos/log/:/home/nacos/logs
    ports:
      - "8848:8848"
      - "9848:9848"
    networks:
     - liwq-tm
    depends_on:
      mysql:
        condition: service_healthy
    restart: always
  mysql:
    container_name: mysql
    image: liwqtm/mysql:8.0.0
    env_file:
      - /app/nacos/nacos-docker/env/mysql.env
    volumes:
      - /app/mysql:/var/lib/mysql
    ports:
      - "3306:3306"
    networks:
      - liwq-tm
    healthcheck:
      test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
      interval: 5s
      timeout: 10s
      retries: 10
networks:
  liwq-tm:
    external: true

Compared with the above, I added a network bridge, so I need to execute docker network create liwq-tmthe command first, and I did not build mysql at startup, but built it first, because in the mysql database corresponding to nacos, some preparatory work must be done first. Create the corresponding database and table, and add some table data, so it is better to operate separately.

Let's first follow the steps to build the mirror image of mysql. Enter the corresponding directory: cd /app/nacos/nacos-docker/example/image/mysql/, execute: docker build -t liwqtm/mysql:8.0.0 ., execute: docker-compose -f 全路径/standalone-mysql-8.yaml up -d, after the startup is successful, you can enter docker exec -t mysql shthe container with the command to check whether there is a nacos_devtest database, or you can use the video software to understand the database.

If this is the database, you can view the corresponding SQL in the official address provided by nacos , and then execute it manually.

If you already have a database and you need to associate it, you need to modify the above mysql file /app/mysqlto your own mysql data storage address when mounting it, then enter the mysql configuration file /app/nacos/nacos-docker/env/mysql.envto modify the user name and user password to your own, and then Enter the configuration file of nacos /app/nacos/nacos-docker/env/nacos-standlone-mysql.env, modify the user name, user password, database name, if the host port exposed by the mysql port is not 3306, it must also be modified.

Then restart, it can also be executed docker-compose -f 全路径/standalone-mysql-8.yaml down. After success, execute the up statement executed above.

In this way, nacos and the corresponding mysql have been successfully installed. We can directly visit http://00.00.00.00:8848/nacos, user name: nacos, user password: nacos.

image-20230414153509452

If the access is not successful, you can look at the log mounted by nacos. After entering the log directory, execute tail -1000f nacos.logto find the specific reason and then solve it.

Here I explain one of the worst exceptions I encountered, NACOS_AUTH_IDENTITY_KEY. At the beginning of this problem, I thought it was caused by not configuring the corresponding database and table. Although I did not, I still have this problem when I configure it later. I searched for a long time on the Internet, and found that the version after nacos 2.2.1 needs to be configured with three attributes to use it. I briefly looked at it, and there are a bunch of secret keys. Fix it on the spot.

nacos has been successfully started in our above content, but it is not considered a successful configuration, because as I said before, the Namespace namespace is the basis for everything to start. If it is not configured, it will use the default public space provided by nacos. Under normal circumstances All need to be configured in advance.

The configuration of the namespace is also very simple. You can directly find the command space on the view page of nacos, and then click the create button. There is almost nothing to pay attention to, and it is a fool's operation.

Notes on mysql data persistence

I added this content later, the reason is that when I woke up one morning, the nacos database in mysql was hacked, all configuration and user data were lost, and I was blackmailed.

The mysql command to create a user and modify permissions is as follows, mainly to modify the password of the root account. You can enter the container to modify the command directly, and then create a nacos database under the root account, and then assign the CRUD permissions of the tables in the database to the nacos user.

If conditions permit, it is best not to expose nacos services to the public network when the project starts, and directly use the docker bridge name, and then open a private server to start the nacos configuration center separately, because the mounted mysql is the same, So don't worry about data out of sync.

mysql create user:

CREATE USER '用户名' @'%' IDENTIFIED BY '密码';

The mysql database grants user privileges:

GRANT SELECT, INSERT, UPDATE, DELETE ON nacos_config.* TO 'nacos' @'%';

The configuration management use of nacos in the project

First, modify the configuration in the pom.xml file. The version I use here is 2.2.7. Different projects need to pay attention to the version of spring cloud. The version of cloud here is Hoxton.SR12.

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2.2.7.RELEASE</version>
</dependency>

After maven is refreshed, you can change application.yml to bootstrap.yml because the latter is loaded more than the former in the automatic loading of spring boot, but it should be noted that it is still a cloud version problem, and versions such as 2022.* are disabled bootstrap.yml is read and written, so it is necessary to introduce a spring boot bootstrap read and write starter.

After the end, we can write the configuration information in yml, but we still need to pay attention not to copy, because if the starter of nacos is imported successfully, there will be a prompt, if not, it means that the starter has not been imported successfully.

spring:
  profiles:
    active: dev #版本名称
  application:
    name: driver # 项目名称
  cloud:
    nacos:
      config:
        server-addr: IP:8848 # nacos 的地址和端口
        namespace: d2f4c55b-815c-4efa-86b2-b1ebb21b6663 # 命令空间的ID
        file-extension: yaml # 配置中心对应的配置文件类型

This configuration in the project is over. There are many other optional configurations in the yml configuration, but none of them are necessary. It can be regarded as the function enhancement of nacos, such as: extended configuration, public configuration and so on. Because nacos also said that the account and password are nacos by default, if you modify the account and password, it is best to configure a username and password.

If you want to isolate the version of the nacos configuration, you can spring.profiles.activeconfigure a corresponding version, and application.namemust be configured, which involves the naming of the nacos configuration file.

After that, you can configure the configuration file on the nacos control panel. In the configuration management of nacos, the create configuration button or the + button can create a configuration. But pay attention to the choice of namespace namespace, which must be consistent with the project.

image-20230425175142391

The configuration information here can be filled in according to the information in the screenshot below. After filling in, be sure to click the publish button.

image-20230425175810586

The configuration can be said to be quite simple. If you edit after publishing and then publish again, nacos will publish an event to the spring multicaster, and then modify the corresponding configuration information by the corresponding response logic, thus achieving dynamic configuration.

If you are editing at the same time, you can also check the beta release, so that only part of the environment can be updated, such as the grayscale release before the official production.

image-20230426162539141

The above basically ends the management of nacos configuration files in the spring cloud project. Another point is that nacos itself can be published in a cluster, but the accessed database is still the same or a high-performance cluster database, that is, data consistency is always maintained. There is no difference for the project, that is, the configuration of the nacos address It is only necessary to configure more than one, or configure one Nginx, and then Nginx will route to the corresponding nacos.

One additional point: For the version control of the nacos configuration center, because the above is dev, it is directly configured as dev in the project. spring.profiles.activeIf it is another version and does not modify bootstrap.yml, it can be executed at runtime -Dspring.profiles.active=版本号, for example: - Dspring.profiles.active=test, if it is started by idea, it can be edited directly. If it is docker, it can be inserted directly when creating the docker image.

image-20230426164341052

The following is the configuration of docker, because I did not use docker in this project, so there is no configuration for the time being, interested friends can go to my docker article for details.

image-20230426165013661

The service discovery of nacos in the project uses

Same as configuration management, first import the starter corresponding to nacos service discovery, which is also in the pom.xml file, pay attention to the version here.

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>2.2.7.RELEASE</version>
</dependency>

Then there is yml configuration, which is the same as when configuring the file above. Pay attention to see if the nacos starter has been successfully imported. If the user name and password are managed, it is best to configure it.

spring:
  profiles:
    active: dev #版本名称
  application:
    name: driver # 项目名称
  cloud:
    nacos:
      discovery:
        server-addr: IP:8848 # nacos 的地址和端口
        namespace: d2f4c55b-815c-4efa-86b2-b1ebb21b6663 # 命令空间的ID

Finally, the startup class configuration of spring boot, which is the class modified by @SpringBootApplication annotation, plus an annotation @EnableDiscoveryClient for service discovery and registration.

@SpringBootApplication
@EnableDiscoveryClient
public class DriverApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(DriverApplication.class,args);
    }
}

In this way, all the configuration is over, because nacos has configured the namespace namespace in advance, so there is no need to configure the content of nacos, just start the project directly.

Here I configured a getway and two driver services, so that you can see that both are injected into nacos, and the driver service has also been monitored for two registrations.

image-20230426173828660

Summarize

The use of configuration center and service discovery of nacos in the cloud project is basically the above content. As for the cluster deployment of nacos, because I don’t have multiple servers here, I won’t demonstrate it. The multi-node deployment of the same service, the official compression of nacos It is included in the package, and it is not much different from single-node deployment. Finally, the follow-up source code process, as well as the joint call completion process between Getway and openfeign, will be discussed in the follow-up source code analysis.
Can.

Here I configured a getway and two driver services, so that you can see that both are injected into nacos, and the driver service has also been monitored for two registrations.

Guess you like

Origin blog.csdn.net/qq_39339965/article/details/130400350