Nacos concept introduces cluster deployment and integrated Springboot use

Participate in the project, use nacos as a service governance tool, use springboot to integrate nacos for service registration service discovery, and monitor service status through nacos. Based on this background, consult nacos related materials, etc., deploy and build a nacos cluster locally, and prepare a demo project to complete the integrated use of springboot and nacos, and realize the functions of service registration discovery and configuration center. The introduction of nacos and the principle of nacos architecture in the first two parts of this article are from the official website of nacos. Here is a brief excerpt and summary. The deployment and use are all derived from actual operation examples. Readers can read and use as needed. There are inevitably omissions in the article, and I hope readers can correct me, thank you very much!

1. Introduction to nacos

1.1 nacos concept

Nacos is dedicated to helping you discover, configure and manage microservices. Nacos provides a set of easy-to-use feature sets to help you quickly realize dynamic service discovery, service configuration, service metadata, and traffic management.

1.2 nacos function

The key features of Nacos extracted from the official website include:

  1. Service discovery and service health monitoring
Nacos支持基于DNS和基于RPC的服务发现,服务端可以通过SDK或者Api进行服务注册,
相应的服务消费者可以使用DNS或者Http查找的方式获取服务列表。
Nacos同时提供对服务的实时健康检查,阻止想不健康的主机或服务发送请求,
与Eureka类似Nacos也有友好的控制台界面。
  1. Dynamic configuration service
动态配置服务可以以中心化、外部化和动态化的方式管理所有环境的应用配置和服务配置。
动态配置消除了配置变更时重新部署应用和服务的需要,让配置管理变得更加高效和敏捷。
配置中心化管理让实现无状态服务变得更简单,让服务按需弹性扩展变得更容易。
Nacos 提供了一个简洁易用的UI (控制台样例 Demo) 帮助您管理所有的服务和应用的配置。
Nacos 还提供包括配置版本跟踪、金丝雀发布、一键回滚配置以及客户端配置更新状态跟踪在内的一系列开箱即用的配置管理特性,帮助您更安全地在生产环境中管理配置变更和降低配置变更带来的风险。
  1. Dynamic DNS service
动态 DNS 服务支持权重路由,让您更容易地实现中间层负载均衡、更灵活的路由策略、流量控制以及数据中心内网的简单DNS解析服务。
动态DNS服务还能让您更容易地实现以 DNS 协议为基础的服务发现,以帮助您消除耦合到厂商私有服务发现 API 上的风险。
Nacos 提供了一些简单的 DNS APIs TODO 帮助您管理服务的关联域名和可用的 IP:PORT 列表.
  1. Services and their metadata management
Nacos 能让您从微服务平台建设的视角管理数据中心的所有服务及元数据,
包括管理服务的描述、生命周期、服务的静态依赖分析、服务的健康状态、服务的流量管理、路由及安全策略、服务的 SLA 以及最首要的 metrics 统计数据。

2. The principle of nacos architecture

2.1 Components

insert image description here

  1. Service Provider
是指提供可复用和可调用服务的应用方。
  1. Service Consumer
是指会发起对某个服务调用的应用方。
  1. Service
服务是指一个或一组软件功能(例如特定信息的检索或一组操作的执行),
其目的是不同的客户端可以为不同的目的重用(例如通过跨进程的网络调用)。
Nacos 支持主流的服务生态,如 Kubernetes Service、gRPC|Dubbo RPC Service 或者 Spring Cloud RESTful Service。
  1. Service Registry
服务注册中心,它是服务,其实例及元数据的数据库。
服务实例在启动时注册到服务注册表,并在关闭时注销。
服务和路由器的客户端查询服务注册表以查找服务的可用实例。
服务注册中心可能会调用服务实例的健康检查 API 来验证它是否能够处理请求。
  1. Service Metadata
服务元数据是指包括服务端点(endpoints)、服务标签、服务版本号、服务实例权重、路由规则、安全策略等描述服务的数据。
  1. Configuration
在系统开发过程中通常会将一些需要变更的参数、变量等从代码中分离出来独立管理,以独立的配置文件的形式存在。
目的是让静态的系统工件或者交付物(如 WAR,JAR 包等)更好地和实际的物理运行环境进行适配。
配置管理一般包含在系统部署的过程中,由系统管理员或者运维人员完成这个步骤。
配置变更是调整系统运行时的行为的有效手段之一。
  1. Configuration Management
在数据中心中,系统中所有配置的编辑、存储、分发、变更管理、历史版本管理、变更审计等所有与配置相关的活动统称为配置管理。
  1. Naming Service
提供分布式系统中所有对象(Object)、实体(Entity)的“名字”到关联的元数据之间的映射管理服务,
例如 ServiceName -> Endpoints Info, Distributed Lock Name -> Lock Owner/Status Info, DNS Domain Name -> IP List, 
服务发现和 DNS 就是名字服务的2大场景。
  1. Configuration Service
在服务或者应用运行过程中,提供动态配置或者元数据以及配置管理的服务提供者。

2.2 APs and CPs

Nacos supports switching between AP and CP modes

Spring Cloud Alibaba Nacos 在 1.0.0 正式支持 AP 和 CP 两种一致性协议,其中 CP一致性协议实现,是基于简化的 Raft 的 CP 一致性。
  1. CAP theory
    Distributed system must be inseparable from CAP theorem, CAP theorem is called Brewer's theorem.
    C (consistency): For a given client, read operations can return the latest write operations. For data distributed on different nodes, if the data is updated on a certain node, then if the latest data can be read on other nodes, it is called strong consistency. If a node does not read If it is obtained, it is distributed inconsistency.
    A (Availability): Non-faulty nodes return reasonable responses (not error and timeout responses) within a reasonable amount of time. The two keys to usability are a reasonable time and a reasonable response. A reasonable time means that the request cannot be blocked indefinitely, and should be returned within a reasonable time. A reasonable response means that the system should return the result clearly and the result is correct.
    P (partition tolerance): When a network partition occurs, the system can continue to work. For example, there are multiple machines in this cluster, and there is a problem with the network of one machine, but the cluster can still work normally.
    The three CAPs cannot be shared. In a distributed system, the network cannot be 100% reliable. Partitioning is actually an inevitable phenomenon. It is theoretically impossible to choose a CA architecture for a distributed system, only CP or AP architecture.

  2. Applicable scenarios of nacos CP and AP
    CP: If you need to edit or store configuration information at the service level, CP is necessary. In CP mode, the registration of persistent instances is supported, and the Raft protocol is used as the cluster operation mode. Before registering an instance in this mode, the service must be registered first. If the service does not exist, an error AP will be returned: If the service level information does not need to be stored and the service
    instance Register through nacos-client and keep heartbeat reporting. AP mode only supports registration of temporary instances. AP protocol: Distro protocol. Distro is Alibaba's private protocol. The current popular Nacos service management framework adopts the Distro protocol. The Distro protocol is positioned as a consistency protocol for temporary data: this type of protocol does not need to store data in disks or databases, because temporary data usually maintains a session session with the server, and as long as the session exists, the data will not be lost. The Distro protocol guarantees that writes must always succeed, even in the event of a network partition. When the network recovers, the data of each data fragment is merged.

3. nacos deployment

3.1 Deployment Mode

Nacos supports three deployment modes:

  1. Stand-alone mode
    for testing and stand-alone trials
  2. Cluster mode
    is used in production environment to ensure high availability
  3. Multi-cluster mode
    for multi-data center scenarios

By default, Nacos uses the embedded database derby to store data. Therefore, if you start multiple Nacos nodes under the default configuration, there will be a consistency problem in data storage. In order to solve this problem, Nacos adopts a centralized storage method to support cluster deployment, and currently only supports mysql storage.

insert image description here
The official website recommends using the combination of dns domain name and load balancer for cluster deployment.
This article uses the cluster mode for deployment, but does not configure the deployment of SLB and DNS processing.

3.2 Cluster Mode Deployment Process

3.2.1 Deployment environment

linux版本:CentOS Linux release 7.2.1511 (Core)
jdk版本:jdk-8u241-linux-x64.tar.gz
nacos版本:nacos-server-2.0.3.tar.gz
nacos下载地址:https://github.com/alibaba/nacos/releases

3.2.2 Deployment steps

  1. Unzip the file
    tar -zvxf nacos-server-2.0.3.tar.gz

  2. Initialize the mysql database, database initialization file: nacos-mysql.sql

create database nacos;
create user nacos identified by 'nacos';
GRANT all on nacos.* to 'nacos'@'%' with grant option;
FLUSH PRIVILEGES;

其中:
	all代表接受所有操作,比如 select,insert,delete....;
	*.* 代表所有库下面的所有表;
	% 代表这个用户允许从任何地方登录;为了安全期间,这个%可以替换为你允许的ip地址;
	flush privileges刷新mysql用户权限相关表;

Execute the nacos-mysql.sql script.
insert image description here
3. Modify the application.properties in the screenshot above, and add the following content (mysql related configuration)

spring.datasource.platform=mysql

### Count of DB:
db.num=1

### Connect URL of DB:
db.url.0=jdbc:mysql://192.168.65.162:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
db.user.0=nacos
db.password.0=nacos

Pay attention to the configuration item in the url: useLegacyDatetimeCode=false&serverTimezone=UTC
If there is no such item, an error will be reported at startup: Nacos Server did not start because dumpservice bean construction failure : No DataSource set

  1. Start and test MySQL on a single machine
sh startup.sh -m standalone

Browser access: http://192.168.65.161:8848/nacos The
insert image description here
default account password is: nacos/nacos
Add a configuration item
insert image description here
MySQL configuration item Database update
insert image description here
The database update is consistent with the system interface, indicating that MySQL configuration is successful.

  1. Modify the cluster configuration file
cp cluster.conf.example cluster.conf
vi cluster.conf
192.168.65.160:8848
192.168.65.161:8848
192.168.65.162:8848
  1. cluster start
sh start.sh

Start the three nodes separately, and view the status information of the three nodes in the interface cluster management-node list
insert image description here

4. springboot integrated nacos use

4.1 Service Discovery and Service Health Monitoring

Springboot uses nacos for service registration and service discovery

  1. Import jar package
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
      <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
      <version>2.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
  1. Add configuration items
spring.application.name=nacos-provider/nacos-consumer
spring.cloud.nacos.server-addr=192.168.65.160:8848,192.168.65.161:8848,192.168.65.162:8848
spring.cloud.nacos.config.server-addr=192.168.65.160:8848,192.168.65.161:8848,192.168.65.162:8848
spring.cloud.nacos.discovery.server-addr=192.168.65.160:8848,192.168.65.161:8848,192.168.65.162:8848
  1. Provider code
    After introducing the above jar package and adding configuration items, provide the restful style api interface in the conventional controller.
@RestController
@RequestMapping("/test/")
public class TestController {

    @RequestMapping("hello")
    public String getTest(String name){
        return "hello:"+name;
    }
}
  1. consumer code
// 1. 启动类中加入 注解 @EnableFeignClients
@EnableFeignClients
@SpringBootApplication
public class App {
    public static void main( String[] args ) {
        SpringApplication.run(App.class);
    }
}

// 2. client工具类,指明服务提供方名称
@FeignClient("nacos-provider")
public interface TestClient {
    @RequestMapping("/test/hello?name={name}")
    String getTestHello(@Valid @PathVariable ("name") String name);
}

// 3. 引入使用即可
@RestController
@RequestMapping("/consume/test")
public class TestController {

    @Autowired
    private TestClient testClient;

    @RequestMapping("hello")
    public String getTest(String name){
        String rest = testClient.getTestHello(name);
        return rest;
    }
}

insert image description here

4.2 Dynamic Configuration Service

  1. Import jar package
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
      <version>2.2.0.RELEASE</version>
    </dependency>
  1. Configuration information bootstrap.properties
spring.application.name=nacos-provider
spring.profiles.active=dev

spring.cloud.nacos.server-addr=192.168.65.160:8848,192.168.65.161:8848,192.168.65.162:8848
spring.cloud.nacos.config.server-addr=192.168.65.160:8848,192.168.65.161:8848,192.168.65.162:8848
spring.cloud.nacos.discovery.server-addr=192.168.65.160:8848,192.168.65.161:8848,192.168.65.162:8848

spring.cloud.nacos.config.file-extension=properties
spring.cloud.nacos.config.group=DEFAULT_GROUP
  1. The data id added by nacos
    can be specified according to spring.application.name-spring.profiles.active in the configuration file
    , and it is specified as properties type here
    insert image description here
    insert image description here

  2. code usage

@RestController
@RequestMapping("/test/")
@RefreshScope
public class TestController {

    @Value("${username}")
    private String username;

    @Value("${userpwd}")
    private String userpwd;

    @RequestMapping("config")
    public String getConfig(){
        return "username:"+username+";userpwd:"+userpwd;
    }
}

5. References

[1] https://nacos.io/
[2] https://www.cnblogs.com/dw3306/p/12961353.html
[3] https://www.cnblogs.com/blogs2002/p/12842250.html
[4] https://blog.csdn.net/weixin_39605835/article/details/111169477

Guess you like

Origin blog.csdn.net/shy871/article/details/120530664