Nestjs combines Nacos to implement configuration center and registration center

what is nacos

nacos is specially designed for registration center and configuration center. It helps you easily build cloud-native applications and microservices platforms. Of course, there are many other middleware, such as Zookeeper and Consul.

  1. The data storage methods are different: Nacos uses a database-based method, while Zookeeper and Consul use memory data structures.
  2. Functional difference: Nacos supports dynamic DNS and multiple data centers. Zookeeper and Consul only support service discovery and configuration management.
  3. Different deployment methods: Nacos can be directly deployed on cloud-native platforms through container orchestration tools such as Docker containers and Kubernetes, while Zookeeper and Consul need to be manually installed and configured.
  4. Different performance and scalability: Nacos has higher performance and scalability than Zookeeper and Consul.

Why do you need a configuration center

Usually, once the service is launched in the back-end development, we will face a problem when modifying the database configuration, log configuration, and environment configuration. We need to repackage and release the version online. It is very troublesome to complete a set of procedures.

Through the dynamic configuration of the configuration center, we can directly adjust it on the visualization page.

image.png

Why do you need a registration center

In distributed microservices, we will use nacos as a service registration center to facilitate management. In short, the registration center means that we can know the specific status information of the service.

Once a node goes down, nacos will automatically log off the current instance, and select a healthy instance to run in the cluster service.

In addition, service information is saved, such as ip, port, cluster information, configuration data, whether to start, health status, etc.

We can simply understand it as service registration and service discovery.

Why do the microservices registered by nacos need to be clustered

To ensure high availability and reliability. In the case of a single node, if the node fails, the registration information of the microservice cannot be discovered and invoked by other microservices, resulting in the unavailability of the entire system.

In the cluster, when a node is unavailable, nacos will load balance to the corresponding available node. At the same time, the performance and scalability of the registration center can be improved through clustering to meet the needs of high concurrency and large-scale microservice registration and discovery.

image.png

install nacos

To install nacos, we only need to download the zip file from the official website and execute the startup file under bin. By default, it will run on port 8848, and the account and password are nacos.

image.png

Integrate nacos in Nestjs

pnpm install nacos-config nacos-naming
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { startNacos } from './nacos';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  startNacos();
  await app.listen(3000);
}

bootstrap();

Bootstrap is the main entrance of nest, and we can inject this method in each microservice.

import { NacosConfigClient } from 'nacos-config';
import { NacosNamingClient } from 'nacos-naming';
const logger = console;
const serviceName = 'nest-user';
const ip = 'localhost';
const port = 3000;
const serverAddr = 'localhost:8848';
const namespace = '3c166fe6-b9c1-45d8-af04-0ade57db8265';
const group =
  process.env.NODE_ENV === 'development' ? 'NEST_USER_DEV' : 'NEST_USER_PRO';
let config = {};

export const setConfig = (cf) => {
  config = cf;
  cf && console.log(`${serviceName}接受到nacos的消息`, JSON.parse(cf));
};
export const getConfig = () => {
  return config;
};

export const startNacos = async () => {
  const client = new NacosNamingClient({
    logger,
    serverList: serverAddr,
    namespace,
  });
  await client.ready();
  await client.registerInstance(
    serviceName,
    {
      ip,
      port,
    },
    group,
  );
  client.subscribe({ serviceName, groupName: group }, (hosts) => {
    console.log('subscribe======', hosts);
  });
  watchNacos();
};

export const deregisterNacos = async (client) => {
  await client.deregisterInstance(serviceName, {
    ip,
    port,
  });
};

const watchNacos = async () => {
  const configClient = new NacosConfigClient({
    serverAddr,
    namespace,
  });
  configClient.subscribe(
    {
      dataId: serviceName,
      group,
    },
    async (content) => {
      setConfig(content);
    },
  );
  configClient.on('error', (err) => {
    console.log('error =====', err);
  });
};

Note that we need to start nacos first, and then run the nest project. Then check whether the service of nacos is registered

image.png

Then we can see from the console that after the logger is defined, the service sends a 5s heartbeat packet to the nacos server. NacosNamingClient is used to initialize service registration. In NacosConfigClient, we can obtain the dynamic configuration of the configuration center.

If your service requires a cluster, then we can client.registerInstanceinstantiate it. Namespace is our scope, which is used to distinguish other services. We need to define a namespace for each microservice. After we run it, we can find it in the nacos page

image.png

Generally, we will distinguish between different environments, such as the development environment name and production environment name defined by the Group.

image.png

Next, let's try dynamic configuration. The json configuration format is used here. We can also choose yaml and Properties.

image.png

In this way, we have received the message, and we can mount it on a global object for easy update.

image.png

Summarize

In springCloud, nacos is highly integrated. In Nestjs, we can also integrate very quickly. nacos provides two very important functions: registration center and configuration center. We can simply understand the registration center as service registration and service discovery.

At the same time, nacos also complies with master-slave replication in terms of consistency. In terms of availability, it is guaranteed by clusters. In terms of partition tolerance, it can quickly partition according to the network environment to meet service availability.

Guess you like

Origin juejin.im/post/7264922511883780108