Alibaba Nacos 学习笔记

Alibaba Nacos

第一章:Nacos 简介

Nacos 集服务发现,服务配置,服务管理为一体能快速实现动态的服务发现、服务配置、服务元数据及流量管理。

Nacos 关键特性:


  • 服务发现与服务健康监测
    • Nacos 支持基于 DNS 和基于 RPC 的服务发现
    • Nacos 提供对服务的实时地健康检查,阻止不健康的主机或服务实例发送请求。
    • Nacos 支持传输层(PING 或 TCP)和应用层(Http、MySQL 等)的健康检查。
  • 动态配置服务
    • 以中心化、外部化和动态化的方式管理所有环境的应用配置和服务配置。
  • 动态 DNS 服务
    • 支持权重路由,更容易的实现中间层负载均衡、更灵活的路由策略、流量控制以及数据中心内网的简单DNS 解析服务。
  • 服务及其元数据管理
    • Nacos 能从微服务平台建设的视角管理数据中心的所有服务及元数据,包括管理服务的描述、生命周期、服务的静态依赖分析、服务的健康状态、服务的流量管理、路由及安全策略、服务的 SLA 以及最首要的 metrics 统计数据。
  • 其他特性详见 Nacos 官方文档

Nacos 生态图:


nacos_landscape.png

Nacos 概念:


Nacos 的基本管理理念

地域

物理的创建中心,资源创建成功后不能更换。

可用区

同一区域内,电力和网络相互独立的物理区域。同一区域内,实例的网络延迟较低。

接入点

地域的某个服务的入口域名

命名空间

用于进行租户粗粒度的配置隔离。不同的命名空间下,可以存在相同的 Group 或 Data ID 的配置。NameSpace 的常用场景之一是不同环境的配置的区分隔离,例如开发测试环境和生产环境的资源(如配置、服务)隔离等。

配置

在系统开发过程中,开发者通常会将一些需要变更的参数、变量等从代码中分离出来独立管理。以独立的配置文件的形式存在。目的是让静态的系统工作或者交付物更好的和实际的物理运行环境进行配置。配置管理一般包含在系统部署的过程中,由系统管理员或者运维人员完成。配置变更时调整系统运行时的行为的有效手段。

配置管理

系统配置的编辑、存储、分发、变更管理、历史版本管理、变更审计等所有与配置相关的活动。

配置项

一个具体的可配置的参数与其值域,通常以param-key=param-value的形式存在。例如我们常配置系统的日志输出级别(logLevel = INFO|WARN|ERROR)就是一个配置项

配置集

一组相关或者不相关的配置项的集合称为配置集。在系统中,一个配置文件通常就是一个配置集,包含了系统各个方面的配置。例如,一个配置集可能包含了数据源、线程池、日志级别等配置项

配置集 ID

Nacos 中的某个配置集的 ID。配置集 ID 是组织划分配置的维度之一。Data ID 通常用于组织划分系统的配置集。一个系统或者应用可以包含多个配置集,每个配置集都可以被一个有意义的名称标识。Data ID 通常采用类 Java 包(如 com.xxxx.xxxx.level )的命名规则保证全局唯一性。命名规则非常强制使用。

配置分组

Nacos 中的一组配置集,是组织配置的维度之一。通过一个有意义的字符串对配置集进行分组,从而区分 Data ID 相同的配置集。当你在 Nacos 上创建一个配置时,如果未填写配置分组的名称,则配置分组的名称默认采用 DEFAULT_GROUP。配置分组的常见场景:不同的应用或组件使用了相同的配置类型,如 database_url 配置和 MQ_topic 配置

配置快照

Nacos 的客户端 SDK 会在本地生成配置的快照。当客户端无法连接到 Nacos Server 时,可以使用配置快照显示系统的整体容灾能力。配置快粘类似于 Git 中的本地 commit ,也类似于缓存,会在适当的时机更新,但是并没有缓存过期(expiration)的概念。

服务

通过预定义接口网络访问的提供给客户端的软件功能

服务名

服务提供的标识,通过该标识可以唯一确定其指代的服务

服务注册中心

存储服务实例和服务负载均衡策略的数据库

服务发现

在计算机网络上,(通常使用服务名)对服务下的实例的地址和元数据进行探测,并以预先定义的接口提供给客户端进行查询

元信息

Nacos 数据(如配置和服务)描述信息,如服务版本、权重、容灾策略、负载均衡策略、鉴权配置、各种定义标签(label),从作用范围来看,分为服务级别的元信息、集群的元信息及实例的元信息

应用

用于标识服务提供方非服务的属性

服务分组

不同的服务可以归类到同一分组

虚拟集群

同一个服务下的所有服务实例组成一个默认集群,集群可以被进一步按需求划分,划分的单位可以是虚拟集群

实例

提供一个或多个服务的具有可访问网络地址(IP:Port)的进程

权重

实例级别的配置,权重为浮点数。权重越大,分配给该实例的流量越大

健康检查

已制定方式检查服务下挂载的实例(Instance)的健康度,从而确认该实例是否能提供服务。根据检查结果,实例会判断为健康或不健康。对服务发起解析请求时,不健康的实例不会返回给客户端

健康保护阈值

为了防止因过多实例不健康导致流量全部流向健康实例,继而造成流量压力把健康实例压垮并形成雪崩效应,应将健康保护阈值定义为一个0到1之间的浮点数。当域名健康实例占服务实例的比例小于该值时,无论是否健康,都会将这个实例返回给客户端。这样虽然损失了一部分流量,但是保证了集群的剩余健康实例能正常工作

Nacos 架构:


基本架构及概念

nacos_arch.jpg

服务 (Service)

服务是指一个或一组软件功能(例如特定信息的检索或一组操作的执行), 其目的是不同客户端可以为不同的目的重用(例如通过夸进程的网络调用)。Nacos 支持主流的服务生态,如 Kubernetes Service、gRPC | Dubbo RPC Service 或者 Spring Cloud RESTFull Service.

服务注册中心 (Service Registry)

服务注册中心,它是服务,其实例及元数据的数据库。服务实例在启动时注册到服务注册表,并在关闭时注销。服务和路由器的客户端查询服务注册表以查找服务的可用实例。服务注册中心可能会调用服务实例的健康检查 API 来验证它是否能够处理请求。

服务元数据 (Service Metadata)

包括服务断点(endpoints)、服务标签、服务版本号、服务实例权重、路由规则、安全策略等描述服务的数据

服务提供方 (Service Provider)

提供可复用和可调用服务的应用方

服务消费者 (Service Consumer)

发起对某个服务调用的应用方

配置(Configuration)

在系统开发过程中通常会将一些需要变更的参数、变量等从代码中分离出来独立管理、以独立的配置文件的形式的存在。目的是让静态的系统工作或者交付物更好的和实际的物理运行进行适配。配置管理一般包含在系统部署的过程中,由系统管理员或者运维人员完成这个步骤。配置变更是调整系统运行时行为的有效手段之一。

配置管理(Configuration Management)

在数据中心中,系统中所有配置的编辑、存储、分发、变更管理、历史版本管理、变更审计等所有与配置相关的活动统称为配置管理

名字服务(Naming Service)

提供分布式系统中所有对象(Object)、实体(Entity)的名字到关联的数据之间的映射管理服务,例如ServiceName->Endpoints Info,Distributed Lock Name->Lock Owner/Status Info, DNS Domain Name->IP List,服务发现和DNS就是名字服务的两大场景

配置服务(Configuration Service)

在服务或者应用运行过程中,提供动态配置或者元数据以及配置管理的服务提供者

其他跟多详见 Nacos 官方

Nacos 逻辑架构及其组件介绍


nacos-logic.jpg

  • 服务管理:实现服务CRUD,域名CRUD,服务健康状态检查,服务权重管理等功能
  • 配置管理:实现配置管CRUD,版本管理,灰度管理,监听管理,推送轨迹,聚合数据等功能
  • 元数据管理:提供元数据CURD 和打标能力
  • 插件机制:实现三个模块可分可合能力,实现扩展点SPI机制
  • 事件机制:实现异步化事件通知,sdk数据变化异步通知等逻辑
  • 日志模块:管理日志分类,日志级别,日志可移植性(尤其避免冲突),日志格式,异常码+帮助文档
  • 回调机制:sdk通知数据,通过统一的模式回调用户处理。接口和数据结构需要具备可扩展性
  • 寻址模式:解决ip,域名,nameserver、广播等多种寻址模式,需要可扩展
  • 推送通道:解决server与存储、server间、server与sdk间推送性能问题
  • 容量管理:管理每个租户,分组下的容量,防止存储被写爆,影响服务可用性
  • 流量管理:按照租户,分组等多个维度对请求频率,长链接个数,报文大小,请求流控进行控制
  • 缓存机制:容灾目录,本地缓存,server缓存机制。容灾目录使用需要工具
  • 启动模式:按照单机模式,配置模式,服务模式,dns模式,或者all模式,启动不同的程序+UI
  • 一致性协议:解决不同数据,不同一致性要求情况下,不同一致性机制
  • 存储模块:解决数据持久化、非持久化存储,解决数据分片问题
  • Nameserver:解决namespace到clusterid的路由问题,解决用户环境与nacos物理环境映射问题
  • CMDB:解决元数据存储,与三方cmdb系统对接问题,解决应用,人,资源关系
  • Metrics:暴露标准metrics数据,方便与三方监控系统打通
  • Trace:暴露标准trace,方便与SLA系统打通,日志白平化,推送轨迹等能力,并且可以和计量计费系统打通
  • 接入管理:相当于阿里云开通服务,分配身份、容量、权限过程
  • 用户管理:解决用户管理,登录,sso等问题
  • 权限管理:解决身份识别,访问控制,角色管理等问题
  • 审计系统:扩展接口方便与不同公司审计系统打通
  • 通知系统:核心数据变更,或者操作,方便通过SMS系统打通,通知到对应人数据变更
  • OpenAPI:暴露标准Rest风格HTTP接口,简单易用,方便多语言集成
  • Console:易用控制台,做服务管理、配置管理等操作
  • SDK:多语言sdk
  • Agent:dns-f类似模式,或者与mesh等方案集成
  • CLI:命令行对产品进行轻量化管理,像git一样好用

领域模型


数据模型

Nacos 数据模型 Key 由三元组唯一确定, Namespace默认是空串,公共命名空间(public),分组默认是 DEFAULT_GROUP。

nacos_data_model

服务领域模型

nacos_naming_data_model

配置领域模型

围绕配置,主要有两个关联的实体,一个是配置变更历史,一个是服务标签(用于打标分类,方便索引),由 ID 关联。

nacos_config_er

类视图

Nacos-SDK 类视图

nacos_sdk_class_relation

构建物、部署及启动模式

undefined

第二章:Nacos 安装

Nacos 支持标准 Docker 镜像(TODO: 0.2版本开始支持)及 zip(tar.gz)压缩包的构建物。

Docker 部署 Nacos 开发环境

GitHub 地址:https://github.com/nacos-group/nacos-docker

目录结构
docker-nacos-standalone
|--docker-compose-nacos.yml
|--nacos-config.sql
|--init.d
|--|--custom.properties
|--prometheus
|--|--prometheus-cluster.yaml
|--|--prometheus-standalone.yaml
  • nacos-config.sql
/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info   */
/******************************************/
CREATE TABLE `config_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) DEFAULT NULL,
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  `c_desc` varchar(256) DEFAULT NULL,
  `c_use` varchar(64) DEFAULT NULL,
  `effect` varchar(64) DEFAULT NULL,
  `type` varchar(64) DEFAULT NULL,
  `c_schema` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_aggr   */
/******************************************/
CREATE TABLE `config_info_aggr` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(255) NOT NULL COMMENT 'group_id',
  `datum_id` varchar(255) NOT NULL COMMENT 'datum_id',
  `content` longtext NOT NULL COMMENT '内容',
  `gmt_modified` datetime NOT NULL COMMENT '修改时间',
  `app_name` varchar(128) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_beta   */
/******************************************/
CREATE TABLE `config_info_beta` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `beta_ips` varchar(1024) DEFAULT NULL COMMENT 'betaIps',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_tag   */
/******************************************/
CREATE TABLE `config_info_tag` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `tag_id` varchar(128) NOT NULL COMMENT 'tag_id',
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL COMMENT 'content',
  `md5` varchar(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` text COMMENT 'source user',
  `src_ip` varchar(50) DEFAULT NULL COMMENT 'source ip',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_tags_relation   */
/******************************************/
CREATE TABLE `config_tags_relation` (
  `id` bigint(20) NOT NULL COMMENT 'id',
  `tag_name` varchar(128) NOT NULL COMMENT 'tag_name',
  `tag_type` varchar(64) DEFAULT NULL COMMENT 'tag_type',
  `data_id` varchar(255) NOT NULL COMMENT 'data_id',
  `group_id` varchar(128) NOT NULL COMMENT 'group_id',
  `tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
  `nid` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`nid`),
  UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = group_capacity   */
/******************************************/
CREATE TABLE `group_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `group_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数,,0表示使用默认值',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = his_config_info   */
/******************************************/
CREATE TABLE `his_config_info` (
  `id` bigint(64) unsigned NOT NULL,
  `nid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `data_id` varchar(255) NOT NULL,
  `group_id` varchar(128) NOT NULL,
  `app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
  `content` longtext NOT NULL,
  `md5` varchar(32) DEFAULT NULL,
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `src_user` text,
  `src_ip` varchar(50) DEFAULT NULL,
  `op_type` char(10) DEFAULT NULL,
  `tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`nid`),
  KEY `idx_gmt_create` (`gmt_create`),
  KEY `idx_gmt_modified` (`gmt_modified`),
  KEY `idx_did` (`data_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = tenant_capacity   */
/******************************************/
CREATE TABLE `tenant_capacity` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `tenant_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID',
  `quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数',
  `max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表';


CREATE TABLE `tenant_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `kp` varchar(128) NOT NULL COMMENT 'kp',
  `tenant_id` varchar(128) default '' COMMENT 'tenant_id',
  `tenant_name` varchar(128) default '' COMMENT 'tenant_name',
  `tenant_desc` varchar(256) DEFAULT NULL COMMENT 'tenant_desc',
  `create_source` varchar(32) DEFAULT NULL COMMENT 'create_source',
  `gmt_create` bigint(20) NOT NULL COMMENT '创建时间',
  `gmt_modified` bigint(20) NOT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';

CREATE TABLE `users` (
	`username` varchar(50) NOT NULL PRIMARY KEY,
	`password` varchar(500) NOT NULL,
	`enabled` boolean NOT NULL
);

CREATE TABLE `roles` (
	`username` varchar(50) NOT NULL,
	`role` varchar(50) NOT NULL,
	UNIQUE INDEX `idx_user_role` (`username` ASC, `role` ASC) USING BTREE
);

CREATE TABLE `permissions` (
    `role` varchar(50) NOT NULL,
    `resource` varchar(255) NOT NULL,
    `action` varchar(8) NOT NULL,
    UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE
);

INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);

INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');
  • custom.properties:
#spring.security.enabled=false
#management.security=false
#security.basic.enabled=false
#nacos.security.ignore.urls=/**
#management.metrics.export.elastic.host=http://localhost:9200
# metrics for prometheus
management.endpoints.web.exposure.include=*

# metrics for elastic search
#management.metrics.export.elastic.enabled=false
#management.metrics.export.elastic.host=http://localhost:9200

# metrics for influx
#management.metrics.export.influx.enabled=false
#management.metrics.export.influx.db=springboot
#management.metrics.export.influx.uri=http://localhost:8086
#management.metrics.export.influx.auto-create-db=true
#management.metrics.export.influx.consistency=one
#management.metrics.export.influx.compressed=true
  • prometheus-cluster.yaml
# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'nacos'
    metrics_path: '/nacos/actuator/prometheus'
    static_configs:
      - targets: ["nacos1:8848","nacos2:8848","nacos3:8848"]
  • prometheus-standalone.yaml
# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'nacos'
    metrics_path: '/nacos/actuator/prometheus'
    static_configs:
      - targets: ['nacos:8848']
  • cluster-embedded.yaml
version: "3"
services:
  nacos1:
    hostname: nacos1
    container_name: nacos1
    image: nacos/nacos-server:1.3.2
    volumes:
      - ./cluster-logs/nacos1:/home/nacos/logs
      - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
      - "8848:8848"
      - "9555:9555"
    env_file:
      - ../env/nacos-embedded.env
    restart: always

  nacos2:
    hostname: nacos2
    image: nacos/nacos-server:1.3.2
    container_name: nacos2
    volumes:
      - ./cluster-logs/nacos2:/home/nacos/logs
      - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
      - "8849:8848"
    env_file:
      - ../env/nacos-embedded.env
    restart: always
  nacos3:
    hostname: nacos3
    image: nacos/nacos-server:1.3.2
    container_name: nacos3
    volumes:
      - ./cluster-logs/nacos3:/home/nacos/logs
      - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
      - "8850:8848"
    env_file:
      - ../env/nacos-embedded.env
    restart: always
  • cluster-hostname.yaml
version: "3"
services:
  nacos1:
    hostname: nacos1
    container_name: nacos1
    image: nacos/nacos-server:latest
    volumes:
      - ./cluster-logs/nacos1:/home/nacos/logs
      - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
      - "8848:8848"
      - "9555:9555"
    env_file:
      - ../env/nacos-hostname.env
    restart: always
    depends_on:
      - mysql

  nacos2:
    hostname: nacos2
    image: nacos/nacos-server:latest
    container_name: nacos2
    volumes:
      - ./cluster-logs/nacos2:/home/nacos/logs
      - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
      - "8849:8848"
    env_file:
      - ../env/nacos-hostname.env
    restart: always
    depends_on:
      - mysql
  nacos3:
    hostname: nacos3
    image: nacos/nacos-server:latest
    container_name: nacos3
    volumes:
      - ./cluster-logs/nacos3:/home/nacos/logs
      - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
      - "8850:8848"
    env_file:
      - ../env/nacos-hostname.env
    restart: always
    depends_on:
      - mysql
  mysql:
    container_name: mysql
    image: nacos/nacos-mysql:5.7
    env_file:
      - ../env/mysql.env
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3306:3306"
  • cluster-ip.yaml
version: "2"
services:
  nacos1:
    image: nacos/nacos-server:latest
    container_name: nacos1
    networks:
      nacos_net:
        ipv4_address: 172.16.238.10
    volumes:
      - ./cluster-logs/nacos1:/home/nacos/logs
    ports:
      - "8848:8848"
      - "9555:9555"
    env_file:
      - ../env/nacos-ip.env
    restart: on-failure
    depends_on:
      - mysql

  nacos2:
    image: nacos/nacos-server:latest
    container_name: nacos2
    networks:
      nacos_net:
        ipv4_address: 172.16.238.11
    volumes:
      - ./cluster-logs/nacos2:/home/nacos/logs
    ports:
      - "8849:8848"
    env_file:
      - ../env/nacos-ip.env
    restart: always
    depends_on:
      - mysql
  nacos3:
    image: nacos/nacos-server:latest
    container_name: nacos3
    networks:
      nacos_net:
        ipv4_address: 172.16.238.12
    volumes:
      - ./cluster-logs/nacos2:/home/nacos/logs
    ports:
      - "8850:8848"
    env_file:
      - ../env/nacos-ip.env
    restart: always
    depends_on:
      - mysql
  mysql:
    container_name: mysql
    image: nacos/nacos-mysql:5.7
    networks:
      nacos_net:
        ipv4_address: 172.16.238.13
    env_file:
      - ../env/mysql.env
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3306:3306"
networks:
  nacos_net:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.16.238.0/24
  • standalone-derby.yaml
version: "2"
services:
  nacos:
    image: nacos/nacos-server:latest
    container_name: nacos-standalone
    environment:
    - PREFER_HOST_MODE=hostname
    - MODE=standalone
    volumes:
    - ./standalone-logs/:/home/nacos/logs
    - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
    - "8848:8848"
  prometheus:
    container_name: prometheus
    image: prom/prometheus:latest
    volumes:
      - ./prometheus/prometheus-standalone.yaml:/etc/prometheus/prometheus.yml
    ports:
      - "9090:9090"
    depends_on:
      - nacos
    restart: on-failure
  grafana:
    container_name: grafana
    image: grafana/grafana:latest
    ports:
      - 3000:3000
    restart: on-failure
  • standalone-mysql-5.7.yaml
version: "2"
services:
  nacos:
    image: nacos/nacos-server:latest
    container_name: nacos-standalone-mysql
    env_file:
      - ../env/nacos-standlone-mysql.env
    volumes:
      - ./standalone-logs/:/home/nacos/logs
      - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
      - "8848:8848"
      - "9555:9555"
    depends_on:
      - mysql
    restart: on-failure
  mysql:
    container_name: mysql
    image: nacos/nacos-mysql:5.7
    env_file:
      - ../env/mysql.env
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3306:3306"
  prometheus:
    container_name: prometheus
    image: prom/prometheus:latest
    volumes:
      - ./prometheus/prometheus-standalone.yaml:/etc/prometheus/prometheus.yml
    ports:
      - "9090:9090"
    depends_on:
      - nacos
    restart: on-failure
  grafana:
    container_name: grafana
    image: grafana/grafana:latest
    ports:
      - 3000:3000
    restart: on-failure
  • standalone-mysql-8.yaml
version: "2"
services:
  nacos:
    image: nacos/nacos-server:1.4.0-BETA
    container_name: nacos-standalone-mysql
    env_file:
      - ../env/nacos-standlone-mysql.env
    volumes:
      - ./standalone-logs/:/home/nacos/logs
      - ./init.d/custom.properties:/home/nacos/init.d/custom.properties
    ports:
      - "8848:8848"
      - "9555:9555"
    depends_on:
      - mysql
    restart: always
  mysql:
    container_name: mysql
    image: nacos/nacos-mysql:8.0.16
    env_file:
      - ../env/mysql.env
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3306:3306"
Docker Nacos 配置参数列表
属性名称描述选项
MODE系统启动方式: 集群/单机cluster/standalone默认 cluster
NACOS_SERVERS集群地址p1:port1空格ip2:port2 空格ip3:port3
PREFER_HOST_MODE支持IP还是域名模式hostname/ip 默认 ip
NACOS_SERVER_PORTNacos 运行端口默认 8848
NACOS_SERVER_IP多网卡模式下可以指定IP
SPRING_DATASOURCE_PLATFORM单机模式下支持MYSQL数据库mysql / 空 默认:空
MYSQL_SERVICE_HOST数据库 连接地址
MYSQL_SERVICE_PORT数据库端口默认 : 3306
MYSQL_SERVICE_DB_NAME数据库库名
MYSQL_SERVICE_USER数据库用户名
MYSQL_SERVICE_PASSWORD数据库用户密码
MYSQL_SERVICE_DB_PARAM数据库连接参数default : characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
MYSQL_DATABASE_NUMIt indicates the number of database默认 :1
JVM_XMS-Xms默认 :2g
JVM_XMX-Xmx默认 :2g
JVM_XMN-Xmn默认 :1g
JVM_MS-XX:MetaspaceSize默认 :128m
JVM_MMS-XX:MaxMetaspaceSize默认 :320m
NACOS_DEBUG是否开启远程DEBUGy/n 默认 :n
TOMCAT_ACCESSLOG_ENABLEDserver.tomcat.accesslog.enabled默认 :false
NACOS_AUTH_SYSTEM_TYPE权限系统类型选择,目前只支持nacos类型默认 :nacos
NACOS_AUTH_ENABLE是否开启权限系统默认 :false
NACOS_AUTH_TOKEN_EXPIRE_SECONDStoken 失效时间默认 :18000
NACOS_AUTH_TOKENtoken默认 :SecretKey012345678901234567890123456789012345678901234567890123456789
NACOS_AUTH_CACHE_ENABLE权限缓存开关 ,开启后权限缓存的更新默认有15秒的延迟默认 : false
MEMBER_LIST通过环境变量的方式设置集群地址例子:192.168.16.101:8847?raft_port=8807,192.168.16.101?raft_port=8808,192.168.16.101:8849?raft_port=8809
EMBEDDED_STORAGE是否开启集群嵌入式存储模式embedded 默认 : none
Zip 方式部署 Nacos 开发环境

运行环境支持

  1. 64 bit OS,支持 Linux/Unix/Mac/Windows,推荐选用 Linux/Unix/Mac。
  2. 64 bit JDK 1.8+;下载 & 配置
  3. Maven 3.2.x+;下载 & 配置
下载&编译
从 GitHub 上下载源码进行编译
git clone https://github.com/alibaba/nacos.git
cd nacos/
mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U  
ls -al distribution/target/

// change the $version to your actual path
cd distribution/target/nacos-server-$version/nacos/bin
下载编译后压缩包

最新版本下载地址

unzip nacos-server-$version.zip 或者 tar -xvf nacos-server-$version.tar.gz
cd nacos/bin
启动服务器
sh startup.sh -m standalone
关闭服务器
sh shutdown.sh

两种启动模式


Nacos 支持将注册中心(Service Registry)与配置中心(Config Center) 在一个进程合并部署或者将2者分离部署的两种模式。

Nacos 功能和需求列表:


Nacos 现依然处于开发、完善过程中,具体功能详见 Nacos 开发需求列表

第三章:Nacos 服务配置中心

Nacos 支持配置中心的配置参数动态更新和读取

Spring Cloud Nacos

POM 依赖
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
Nacos 配置列表中新建配置

image-20201226153449728

image-20201226153404862

Data ID : nacos-config.properties
Group : DEFAULT_GROUP
Configuration format: Properties
Configuration content:   
	user.name=nacos-config-properties
    user.age=90
Spring Cloud 客户端配置参数设置

bootstrap.properties

# DataId By default, the `spring.application.name` configuration is combined with the file extension (the configuration format uses properties by default), and the GROUP is not configured to use DEFAULT_GROUP by default. Therefore, the Nacos Config configuration corresponding to the configuration file has a DataId of nacos-config.properties and a GROUP of DEFAULT_GROUP
spring.application.name=nacos-config	# 默认获取的是 Data ID 跟项目注册名称一样的配置信息
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
Spring Cloud 客户端获取 Nacos 配置中心参数
@SpringBootApplication
public class NacosConfigApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosConfigApplication.class, args);
        String userName = applicationContext.getEnvironment().getProperty("user.name");
        String userAge = applicationContext.getEnvironment().getProperty("user.age");
        System.err.println("user name :" +userName+"; age: "+userAge);
    }
}
读取不同格式的配置文件

spring.cloud.nacos.config.file-extension=yaml

Nacos 支持多级别配置

-Dspring.profiles.active=<profile> 在运行时快捷指定其运行级别

Spring Application 运行级别

spring.profile.active=develop

Nacos 多级别配置

nacos-config-develop.yaml

image-20201226163359584

Data ID: nacos-config-develop.yaml 
Group : DEFAULT_GROUP 
Configuration format: YAML
Configuration content: current.env: develop-env

nacos-config-product.yaml

image-20201226163555947

Data ID: nacos-config-product.yaml
Group : DEFAULT_GROUP
Configuration format: YAML
Configuration content: current.env: product-env

第四章:Nacos 服务提供者注册

Nacos Spring Boot

Nacos 服务提供者注册+服务配置 provider+configuration
依赖的引入
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>${nacos-config-spring-boot.version}</version>
</dependency>

<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-actuator</artifactId>
    <version>${nacos-config-spring-boot.version}</version>
</dependency>
配置管理
server.port=8082
spring.application.name=nacos-spring-boot-example-consumer

nacos.config.server-addr=127.0.0.1:8848

# endpoint http://localhost:8080/actuator/nacos-config
# health http://localhost:8080/actuator/health
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
实体类简析

NacosConfigApplication

@SpringBootApplication
// 使用 @NacosPropertySource 加载 dataId 为 example 的配置源,并开启自动更新
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class NacosConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosConfigApplication.class, args);
    }
}

@Controller
@RequestMapping("config")
public class ConfigController {

    // 通过 Nacos 的 @NacosValue 注解设置属性值
    @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
    private boolean useLocalCache;

    @RequestMapping(value = "/get", method = GET)
    @ResponseBody
    public boolean get() {
        return useLocalCache;
    }
}
Nacos 服务消费者 consumer
依赖的引入
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-discovery-spring-boot-starter</artifactId>
    <version>${nacos-discovery-spring-boot.version}</version>
</dependency>
配置管理
server:
  port: 8082
spring:
  application:
    name: nacos-spring-boot-example-consumer

  cloud:
    nacos:
      discovery:
        server-addr: 192.168.111.153:8848
management:
  endpoints:
    web:
      exposure:
        include: "*"
实体类简析

NacosDiscoveryApplication

@Controller
@RequestMapping("discovery")
public class DiscoveryController {

    @NacosInjected
    private NamingService namingService;

    @RequestMapping(value = "/get", method = GET)
    @ResponseBody
    public List<Instance> get(@RequestParam String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }
}

@SpringBootApplication
public class NacosDiscoveryApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosDiscoveryApplication.class, args);
    }
}

Nacos Spring Cloud

Nacos 服务提供者注册 provider
依赖的引入
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置管理
server:
  port: 8081
spring:
  application:
    name: nacos-spring-boot-example-provider
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.111.153:8848
management:
  endpoints:
    web:
      exposure:
        include: "*"
实体类简析

NacosProdiverApplication

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

    @RestController
    public class EchoController{
        @GetMapping(value = "/echo/{string}")
        public String echo(@PathVariable String string){
            return "Hello Nacos Discovery " + string;
        }
    }
}


第五章:Nacos 服务消费者注册和负载均衡

Nacos Spring Cloud

Nacos 服务消费者 consumer
依赖的引入
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置管理
server:
  port: 8082
spring:
  application:
    name: nacos-spring-boot-example-consumer

  cloud:
    nacos:
      discovery:
        server-addr: 192.168.111.153:8848
management:
  endpoints:
    web:
      exposure:
        include: "*"
实体类简析

NacosDiscoveryApplication

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

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @RestController
    public class NacosConsumerController {
        @Autowired
        private LoadBalancerClient loadBalancerClient;
        @Autowired
        private RestTemplate restTemplate;
        @Value("${spring.application.name}")
        private String appName;

        @GetMapping("/echo/app-name")
        public String echoAppName() {
            // 负载均衡的方式获取 Nacos 服务提供者的客户端
            ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-spring-boot-example-provider");
            String url = String.format("http://%s:%s/echo/%s", serviceInstance.getHost(), serviceInstance.getPort(), appName);
//            String url = "http://localhost:8081/echo/" + appName;
            System.out.println("request url: " + url);
            // http://服务提供者ip:服务提供者端口/服务调用路径
            return restTemplate.getForObject(url, String.class);
        }
    }
}

Nacos 和 OpenFeign 实现负载均衡

  1. nacos 注册中心,自带负载均衡功能
  2. nacos 和 openfeign 能更简单的实现负载均衡
POM 依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
使用 @EnableFeignClients 开启 Feign 功能
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosConsumerApplication.class, args);
    }
}
Service 实现
@FeignClient(value = "nacos-spring-boot-example-provider")
public interface EchoService {
    @GetMapping(value = "/echo/{string}")
    String echo (@PathVariable(value = "string") String string);
}
Controller层调用
@RestController
public class EchoController {
    @Autowired
    private EchoService echoService;

    @GetMapping(value = "/feign/echo/{string}")
    public String echo(@PathVariable String string){
        return echoService.echo(string);
    }
}

负载均衡策略

轮循

Round Robin: 这种方法会将收到的请求循环分配到服务器集群中的每台机器,即有效服务器。如果使用这种方式,所有的标记进入虚拟服务的服务器应该有相近的资源容量 以及负载形同的应用程序。如果所有的服务器有相同或者相近的性能那么选择这种方式会使服务器负载形同。基于这个前提,轮循调度是一个简单而有效的分配请求 的方式。然而对于服务器不同的情况,选择这种方式就意味着能力比较弱的服务器也会在下一轮循环中接受轮循,即使这个服务器已经不能再处理当前这个请求了。 这可能导致能力较弱的服务器超载。

加权轮循

Weighted Round Robin: 这种算法解决了简单轮循调度算法的缺点:传入的请求按顺序被分配到集群中服务器,但是会考虑提前为每台服务器分配的权重。管理员只是简单的通过服务 器的处理能力来定义各台服务器的权重。例如,能力最强的服务器 A 给的权重是 100,同时能力最低的服务器给的权重是 50。这意味着在服务器 B 接收到第一个 请求之前前,服务器 A 会连续的接受到 2 个请求,以此类推。

最少连接数

Least Connection: 以上两种方法都没有考虑的是系统不能识别在给定的时间里保持了多少连接。因此可能发生,服务器 B 服务器收到的连接比服务器 A 少但是它已经超载,因为 服务器 B 上的用户打开连接持续的时间更长。这就是说连接数即服务器的负载是累加的。这种潜在的问题可以通过 “最少连接数” 算法来避免:传入的请求是根据每 台服务器当前所打开的连接数来分配的。即活跃连接数最少的服务器会自动接收下一个传入的请求。接本上和简单轮询的原则相同:所有拥有虚拟服务的服务器资源 容量应该相近。值得注意的是,在流量率低的配置环境中,各服务器的流量并不是相同的,会优先考虑第一台服务器。这是因为,如果所有的服务器是相同的,那么 第一个服务器优先,直到第一台服务器有连续的活跃流量,否则总是会优先选择第一台服务器。

源 IP 哈希

Source IP Hash: 这种方式通过生成请求源 IP 的哈希值,并通过这个哈希值来找到正确的真实服务器。这意味着对于同一主机来说他对应的服务器总是相同。使用这种方式,你不需要保存任何源 IP。但是需要注意,这种方式可能导致服务器负载不平衡。

最少连接数慢启动时间

Least Connection Slow Start Time: 对最少连接数和带权重的最小连接数调度方法来说,当一个服务器刚加入线上环境是,可以为其配置一个时间段,在这段时间内连接数是有限制的而且是缓慢 增加的。这为服务器提供了一个‘过渡时间’以保证这个服务器不会因为刚启动后因为分配的连接数过多而超载。这个值在 L7 配置界面设置。

加权最少连接

Weighted Least Connection: 如果服务器的资源容量各不相同,那么 “加权最少连接” 方法更合适:由管理员根据服务器情况定制的权重所决定的活跃连接数一般提供了一种对服务器非常 平衡的利用,因为他它借鉴了最少连接和权重两者的优势。通常,这是一个非常公平的分配方式,因为它使用了连接数和服务器权重比例;集群中比例最低的服务器 自动接收下一个请求。但是请注意,在低流量情况中使用这种方法时,请参考 “最小连接数” 方法中的注意事项。

基于代理的自适应负载均衡

Agent Based Adaptive Balancing: 除了上述方法之外,负载主机包含一个自适用逻辑用来定时监测服务器状态和该服务器的权重。对于非常强大的 “基于代理的自适应负载均衡” 方法来说,负 载主机以这种方式来定时检测所有服务器负载情况:每台服务器都必须提供一个包含文件,这个文件包含一个 0~99 的数字用来标明改服务器的实际负载情况 (0 = 空前,99 = 超载,101 = 失败,102 = 管理员禁用),而服务器同构 http get 方法来获取这个文件;同时对集群中服务器来说,以二进制文件形式提供自身负载情况也是该服务器工作之一,然而,并没有限制服务器如何计算自身的负载 情况。根据服务器整体负载情况,有两种策略可以选择:在常规的操作中,调度算法通过收集的服务器负载值和分配给该服务器的连接数的比例计算出一个权重比 例。因此,如果一个服务器负载过大,权重会通过系统透明的作重新调整。和加权轮循调度方法一样,不正确的分配可以被记录下来使得可以有效的为不同服务器分 配不同的权重。然而,在流量非常低的环境下,服务器报上来的负载值将不能建立一个有代表性的样本;那么基于这些值来分配负载的话将导致失控以及指令震荡。 因此,在这种情况下更合理的做法是基于静态的权重比来计算负载分配。当所有服务器的负载低于管理员定义的下限时,负载主机就会自动切换为加权轮循方式来分 配请求;如果负载大于管理员定义的下限,那么负载主机又会切换回自适应方式。

固定权重

Fixed Weighted: 最高权重只有在其他服务器的权重值都很低时才使用。然而,如果最高权重的服务器下降,则下一个最高优先级的服务器将为客户端服务。这种方式中每个真实服务器的权重需要基于服务器优先级来配置。

加权响应

Weighted Response: 流量的调度是通过加权轮循方式。加权轮循中所使用的权重是根据服务器有效性检测的响应时间来计算。每个有效性检测都会被计时,用来标记它响应成功花 了多长时间。但是需要注意的是,这种方式假定服务器心跳检测是基于机器的快慢,但是这种假设也许不总是能够成立。所有服务器在虚拟服务上的响应时间的总和 加在一起,通过这个值来计算单个服务物理服务器的权重;这个权重值大约每 15 秒计算一次。

第六章:Nacos 服务注册中心对比

第七章:Nacos 参数详解

Nacos 查找配置方式途径:

​ namespace --> group --> DataID

Nacos 完整配置

server.port=8080
spring.application.name=spring-cloud-nacos-consumer
spring.profiles.active=dev

spring.cloud.nacos.config.server-addr=192.168.111.153:8848
spring.cloud.nacos.config.namespace=06978ccc-4e9b-475d-931e-da834d62d99d
spring.cloud.nacos.config.file-extension=yaml

spring.cloud.nacos.config.ext-config[0].data-id=nacos-hello-consumer.yml

spring.cloud.nacos.config.ext-config[1].data-id=nacos-hello-consumer01.yml
spring.cloud.nacos.config.ext-config[1].group=GLOBALE_GROUP

spring.cloud.nacos.config.ext-config[2].data-id=nacos-hello-consumer02.yml
spring.cloud.nacos.config.ext-config[2].group=GLOBALE_GROUP
spring.cloud.nacos.config.ext-config[2].refresh=true

7.1 DataID


Nacos 中的某个配置集的 ID。配置集 ID 是组织划分配置的维度之一。Data ID 通常用于组织划分系统的配置集。一个系统或者应用可以包含多个配置集,每个配置集都可以被一个有意义的名称标识。Data ID 通常采用类 Java 包(如 com.taobao.tc.refund.log.level)的命名规则保证全局唯一性。此命名规则非强制。

配置方式一
spring.application.name=opensource-service-provider
spring.cloud.nacos.config.server-addr=127.0.0.1:8848

# config external configuration
# 1. Data Id is in the default group of DEFAULT_GROUP, and dynamic refresh of configurations is not supported.
spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties

# 2. Data Id is not in the default group, and dynamic refresh of configurations is not supported.
spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties
spring.cloud.nacos.config.ext-config[1].group=GLOBALE_GROUP

# 3. Data Id is not in the default group and dynamic referesh of configurations is supported.
spring.cloud.nacos.config.ext-config[2].data-id=ext-config-common03.properties
spring.cloud.nacos.config.ext-config[2].group=REFRESH_GROUP
spring.cloud.nacos.config.ext-config[2].refresh=true
配置方式二
# 多配置文件读取
spring.cloud.nacos.config.shared-dataids=bootstrap-common.properties,all-common.properties
# 动态刷新配置文件读取
spring.cloud.nacos.config.refreshable-dataids=bootstrap-common.properties

7.2 Group


Nacos 中的一组配置集,是组织配置的维度之一。通过一个有意义的字符串(如 Buy 或 Trade )对配置集进行分组,从而区分 Data ID 相同的配置集。当您在 Nacos 上创建一个配置时,如果未填写配置分组的名称,则配置分组的名称默认采用 DEFAULT_GROUP 。配置分组的常见场景:不同的应用或组件使用了相同的配置类型,如 database_url 配置和 MQ_topic 配置。

spring.cloud.nacos.config.group=DEVELOP_GROUP
spring.cloud.nacos.discovery.group=DEVELOP_GROUP

image-20201226165110371

7.3 Namespace


用于进行租户粒度的配置隔离。不同的命名空间下,可以存在相同的 Group 或 Data ID 的配置。Namespace 的常用场景之一是不同环境的配置的区分隔离,例如开发测试环境和生产环境的资源(如配置、服务)隔离等。

# 这两个配置必须在 bootstrap.yml 中才能生效
spring.cloud.nacos.config.namespace=b3404bc0-d7dc-4855-b519-570ed34b62d7
spring.cloud.nacos.discovery.namespace=b3404bc0-d7dc-4855-b519-570ed34b62d7

image-20201226164514632

image-20201226164603407

第八章:Nacos 集群的搭建与数据持久化

Nacos 支持三种部署模式:

​ 单机模式:用于测试和单机模式

​ 集群模式:用于生产环境、确保高可用

​ 多集群模式:用于多数据中心场景

单机模式

0.7版本之前在单机模式中 Nacos 使用嵌入式数据库实现数据的存储,不方便观察数据的基本情况。0.7版本之后 Nacos 增加了支持 MySQL 数据源能力

  • 安装数据库,版本:5.6.5+

  • 初始化数据库,数据库初始化文件 nacos-mysql.sql

  • 修改 conf/applicaiton.preperties 文件,增加支持 mysql 数据源配置

    spring.datasource.platform=mysql
    
    db.num=1
    db.url.0=jdbc:mysql://11.162.196.16:3306/nacos_devtest?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
    db.user=root
    db.password=123456
    

集群模式

Nacos 集群架构图

deployDnsVipMode.jpg

下载并编译
unzip nacos-source.zip  # Git 上源码
cd nacos/
mvn -Prelease-nacos clean install -U  
cd nacos/distribution/target/nacos-server-1.3.0/nacos/bin
配置集群配置文件

在nacos的解压目录nacos/的conf目录下,有配置文件cluster.conf,请每行配置成ip:port

# ip:port
192.168.111.153:8850
192.168.111.153:8851
192.168.111.153:8852
数据源配置

推荐使用高可用的主从数据库集群

初始化数据库

sql 文件

application.properties 配置参考

application.properties

#
# Copyright 1999-2018 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#*************** Spring Boot Related Configurations ***************#
### Default web context path:
server.servlet.contextPath=/nacos
### Default web server port:
server.port=8848

#*************** Network Related Configurations ***************#
### If prefer hostname over ip for Nacos server addresses in cluster.conf:
# nacos.inetutils.prefer-hostname-over-ip=false

### Specify local server's IP:
# nacos.inetutils.ip-address=


#*************** Config Module Related Configurations ***************#
### If use MySQL as datasource:
# spring.datasource.platform=mysql

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

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


#*************** Naming Module Related Configurations ***************#
### Data dispatch task execution period in milliseconds:
# nacos.naming.distro.taskDispatchPeriod=200

### Data count of batch sync task:
# nacos.naming.distro.batchSyncKeyCount=1000

### Retry delay in milliseconds if sync task failed:
# nacos.naming.distro.syncRetryDelay=5000

### If enable data warmup. If set to false, the server would accept request without local data preparation:
# nacos.naming.data.warmup=true

### If enable the instance auto expiration, kind like of health check of instance:
# nacos.naming.expireInstance=true

nacos.naming.empty-service.auto-clean=true
nacos.naming.empty-service.clean.initial-delay-ms=50000
nacos.naming.empty-service.clean.period-time-ms=30000


#*************** CMDB Module Related Configurations ***************#
### The interval to dump external CMDB in seconds:
# nacos.cmdb.dumpTaskInterval=3600

### The interval of polling data change event in seconds:
# nacos.cmdb.eventTaskInterval=10

### The interval of loading labels in seconds:
# nacos.cmdb.labelTaskInterval=300

### If turn on data loading task:
# nacos.cmdb.loadDataAtStart=false


#*************** Metrics Related Configurations ***************#
### Metrics for prometheus
#management.endpoints.web.exposure.include=*

### Metrics for elastic search
management.metrics.export.elastic.enabled=false
#management.metrics.export.elastic.host=http://localhost:9200

### Metrics for influx
management.metrics.export.influx.enabled=false
#management.metrics.export.influx.db=springboot
#management.metrics.export.influx.uri=http://localhost:8086
#management.metrics.export.influx.auto-create-db=true
#management.metrics.export.influx.consistency=one
#management.metrics.export.influx.compressed=true


#*************** Access Log Related Configurations ***************#
### If turn on the access log:
server.tomcat.accesslog.enabled=true

### The access log pattern:
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i

### The directory of access log:
server.tomcat.basedir=


#*************** Access Control Related Configurations ***************#
### If enable spring security, this option is deprecated in 1.2.0:
#spring.security.enabled=false

### The ignore urls of auth, is deprecated in 1.2.0:
nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**

### The auth system to use, currently only 'nacos' is supported:
nacos.core.auth.system.type=nacos

### If turn on auth system:
nacos.core.auth.enabled=false

### The token expiration in seconds:
nacos.core.auth.default.token.expire.seconds=18000

### The default token:
nacos.core.auth.default.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789

### Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay.
nacos.core.auth.caching.enabled=true


#*************** Istio Related Configurations ***************#
### If turn on the MCP server:
nacos.istio.mcp.server.enabled=false



###*************** Add from 1.3.0 ***************###


#*************** Core Related Configurations ***************#

### set the WorkerID manually
# nacos.core.snowflake.worker-id=

### Member-MetaData
# nacos.core.member.meta.site=
# nacos.core.member.meta.adweight=
# nacos.core.member.meta.weight=

### MemberLookup
### Addressing pattern category, If set, the priority is highest
# nacos.core.member.lookup.type=[file,address-server]
## Set the cluster list with a configuration file or command-line argument
# nacos.member.list=192.168.16.101:8847?raft_port=8807,192.168.16.101?raft_port=8808,192.168.16.101:8849?raft_port=8809
## for AddressServerMemberLookup
# Maximum number of retries to query the address server upon initialization
# nacos.core.address-server.retry=5
## Server domain name address of [address-server] mode
# address.server.domain=jmenv.tbsite.net
## Server port of [address-server] mode
# address.server.port=8080
## Request address of [address-server] mode
# address.server.url=/nacos/serverlist

#*************** JRaft Related Configurations ***************#

### Sets the Raft cluster election timeout, default value is 5 second
# nacos.core.protocol.raft.data.election_timeout_ms=5000
### Sets the amount of time the Raft snapshot will execute periodically, default is 30 minute
# nacos.core.protocol.raft.data.snapshot_interval_secs=30
### raft internal worker threads
# nacos.core.protocol.raft.data.core_thread_num=8
### Number of threads required for raft business request processing
# nacos.core.protocol.raft.data.cli_service_thread_num=4
### raft linear read strategy. Safe linear reads are used by default, that is, the Leader tenure is confirmed by heartbeat
# nacos.core.protocol.raft.data.read_index_type=ReadOnlySafe
### rpc request timeout, default 5 seconds
# nacos.core.protocol.raft.data.rpc_request_timeout_ms=5000
启动服务器
使用内置数据源
sh startup.sh -p embedded
使用外置数据源
sh startup.sh
关闭服务器
sh shutdown.sh

多集群模式

Nacos 支持 NameServer 路由请求模式, 通过它可以设计一个有用的映射规则来控制请求转发到相应的集群。

多网卡IP选择

当本地环境比较复杂的时候, Naocs 服务在启动的时候需要选择运行时使用的 IP 或者网卡。nacos 从多网卡获取 IP

  • ip-address参数可以直接设置nacos的ip

    nacos.inetutils.ip-address=10.11.105.155
    
  • use-only-site-local-interfaces参数可以让nacos使用局域网ip,这个在nacos部署的机器有多网卡时很有用,可以让nacos选择局域网网卡

    nacos.inetutils.use-only-site-local-interfaces=true
    
  • ignored-interfaces支持网卡数组,可以让nacos忽略多个网卡

    nacos.inetutils.ignored-interfaces[0]=eth0
    nacos.inetutils.ignored-interfaces[1]=eth1
    
  • preferred-networks参数可以让nacos优先选择匹配的ip,支持正则匹配和前缀匹配

    nacos.inetutils.preferred-networks[0]=30.5.124.
    nacos.inetutils.preferred-networks[0]=30.5.124.(25[0-5]|2[0-4]\\d|((1d{2})|([1-9]?\\d))),30.5.124.(25[0-5]|2[0-4]\\d|((1d{2})|([1-9]?\\d)))
    

第九章:Nacos 控制台管理

服务管理


通过友好的界面来查看服务的注册情况,包括当前系统注册的所有服务和每个服务的详情。并在有权限控制的情况下,进行服务的一些配置的编辑操作

服务列表及服务健康状态展示

服务列表帮助用户以统一的视图管理其所有的微服务以及服务健康状态。整体界面布局是左上角有服务的搜索框和搜索按钮,页面中央是服务列表的展示。服务列表主要展示服务名、集群数目、实例数目、健康实例数目和详情按钮五个栏目。

在服务列表页面点击详情,可以看到服务的详情。可以查看服务、集群和实例的基本信息。

服务元数据存储及编辑

Nacos提供多个维度的服务元数据的暴露,帮助用户存储自定义的信息。这些信息都是以K-V的数据结构存储,在控制台上,会以k1=v1,k2=v2这样的格式展示。类似的,编辑元数据可以通过相同的格式进行。例如服务的元数据编辑,首先点击服务详情页右上角的“编辑服务”按钮,然后在元数据输入框输入:version=1.0,env=prod。

image.png | left | 747x271

服务流量权重的调整

Nacos 为用户提供了流量权重控制的能力,同时开放了服务流量的阈值保护,以帮助用户更好的保护服务服务提供者集群不被意外打垮。如下图所以,可以点击实例的编辑按钮,修改实例的权重。如果想增加实例的流量,可以将权重调大,如果不想实例接收流量,则可以将权重设为0。

image.png | left | 747x266

服务优雅上下线

Nacos还提供服务实例的上下线操作,在服务详情页面,可以点击实例的“上线”或者“下线”按钮,被下线的实例,将不会包含在健康的实例列表里。

配置管理


Nacos支持基于Namespace和Group的配置分组管理,以便用户更灵活的根据自己的需要按照环境或者应用、模块等分组管理微服务以及Spring的大量配置,在配置管理中主要提供了配置历史版本、回滚、订阅者查询等核心管理能力。

多种配置格式编辑

Nacos支持 YAML、Properties、TEXT、JSON、XML、HTML 等常见配置格式在线编辑、语法高亮、格式校验,帮助用户高效编辑的同时大幅降低格式错误带来的风险。

Nacos支持配置标签的能力,帮助用户更好、更灵活的做到基于标签的配置分类及管理。同时支持用户对配置及其变更进行描述,方面多人或者跨团队协作管理配置。

编辑DIFF

Nacos支持编辑DIFF能力,帮助用户校验修改内容,降低改错带来的风险。

推送状态查询

Nacos提供配置订阅者即监听者查询能力,同时提供客户端当前配置的MD5校验值,以便帮助用户更好的检查配置变更是否推送到 Client 端。

配置版本及一键回滚

Nacos通过提供配置版本管理及其一键回滚能力,帮助用户改错配置的时候能够快速恢复,降低微服务系统在配置管理上的一定会遇到的可用性风险。

命名空间


Nacos 基于Namespace 帮助用户逻辑隔离多个命名空间,这可以帮助用户更好的管理测试、预发、生产等多环境服务和配置,让每个环境的同一个配置(如数据库数据源)可以定义不同的值。

登录管理


修改默认用户名/密码方法
  1. 生成加密密码, 在com.alibaba.nacos.console.utils.PasswordEncoderUtil.main函数中,将 nacos 改成你要改成的密码,运行即可得到加密有算法。注意盐值是随机的,所以生成密码每次可能不一样,请不要担心。

    public class PasswordEncoderUtil {
    
        public static void main(String[] args) {
            System.out.println(new BCryptPasswordEncoder().encode("nacos"));
        }
    }
    
  2. 创建用户名或者密码的时候,用指定用户名密码即可。

    INSERT INTO users (username, password, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);
    INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');
    
关闭登录功能

由于部分公司自己开发控制台,不希望被nacos的安全filter拦截。因此nacos支持定制关闭登录功能找到配置文件 ${nacoshome}/conf/application.properties, 替换以下内容即可。

## spring security config
### turn off security
spring.security.enabled=false
management.security=false
security.basic.enabled=false
nacos.security.ignore.urls=/**

#nacos.security.ignore.urls=/,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/v1/auth/login,/v1/console/health,/v1/cs/**,/v1/ns/**,/v1/cmdb/**,/actuator/**
会话时间

默认会话保持时间为30分钟。30分钟后需要重新登录认证。 暂时不支持修改该默认时间。

第十章:Nacos 权限认证 鉴权

鉴权

服务端开启鉴权
非 Docker 环境

开启鉴权之前,application.properties中的配置信息为:

### If turn on auth system:
nacos.core.auth.enabled=false

开启鉴权之后,application.properties中的配置信息为:

### If turn on auth system:
nacos.core.auth.enabled=true
Docker环境

如果使用官方镜像,请在启动docker容器时,添加如下环境变量

NACOS_AUTH_ENABLE=true

例如,可以通过如下命令运行开启了鉴权的容器:

docker run --env PREFER_HOST_MODE=hostname --env MODE=standalone --env NACOS_AUTH_ENABLE=true -p 8848:8848 nacos/nacos-server

除此之外,还可以添加其他鉴权相关的环境变量信息:

namedescriptionoption
NACOS_AUTH_ENABLE是否开启权限系统默认:false
NACOS_AUTH_TOKEN_EXPIRE_SECONDStoken 失效时间默认:18000
NACOS_AUTH_TOKENtoken默认:SecretKey012345678901234567890123456789012345678901234567890123456789
NACOS_AUTH_CACHE_ENABLE权限缓存开关 ,开启后权限缓存的更新默认有15秒的延迟默认 : false

然后运行docker-compose构建命令,例如

docker-compose -f example/standalone-derby.yaml up
自定义镜像

在构建镜像之前,修改nacos工程中的application.properties文件,

将下面这一行配置信息

nacos.core.auth.enabled=false

修改为

nacos.core.auth.enabled=true

然后再配置nacos启动命令。

客户端进行鉴权
Java SDK鉴权

在构建“Properties”类时,需传入用户名和密码。

properties.put("username","${username}");
properties.put("password","${password}");

示例代码

try {
    // Initialize the configuration service, and the console automatically obtains the following parameters through the sample code.
	String serverAddr = "{serverAddr}";
	Properties properties = new Properties();
	properties.put("serverAddr", serverAddr);

    // if need username and password to login
        properties.put("username","nacos");
        properties.put("password","nacos");

	ConfigService configService = NacosFactory.createConfigService(properties);
} catch (NacosException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Open-API 鉴权

首先需要使用用户名和密码登陆nacos。

curl -X POST '127.0.0.1:8848/nacos/v1/auth/login' -d 'username=nacos&password=nacos'

若用户名和密码正确,返回信息如下:

{"accessToken":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJuYWNvcyIsImV4cCI6MTYwNTYyOTE2Nn0.2TogGhhr11_vLEjqKko1HJHUJEmsPuCxkur-CfNojDo","tokenTtl":18000,"globalAdmin":true}

接下来进行配置信息或服务信息时,应当使用该accessToken鉴权,在url后添加参数accessToken={accessToken},其中{accessToken}为登录时返回的token信息,例如

curl -X GET '127.0.0.1:8848/nacos/v1/cs/configs?accessToken=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJuYWNvcyIsImV4cCI6MTYwNTYyMzkyM30.O-s2yWfDSUZ7Svd3Vs7jy9tsfDNHs1SuebJB4KlNY8Q&dataId=nacos.example.1&group=nacos_group'
curl -X POST 'http://127.0.0.1:8848/nacos/v1/ns/instance?accessToken=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJuYWNvcyIsImV4cCI6MTYwNTYyMzkyM30.O-s2yWfDSUZ7Svd3Vs7jy9tsfDNHs1SuebJB4KlNY8Q&port=8848&healthy=true&ip=11.11.11.11&weight=1.0&serviceName=nacos.test.3&encoding=GBK&namespaceId=n1'

第十一章:Nacos 系统参数

Nacos Server

对于Server端来说,一般是设置在{nacos.home}/conf/application.properties里,如果参数名后标注了(-D)的,则表示是 JVM 的参数,需要在{nacos.home}/bin/startup.sh里进行相应的设置。例如像设置 nacos.home 的值,可以在{nacos.home}/bin/startup.sh进行如下设置:

JAVA_OPT="${JAVA_OPT} -Dnacos.home=${BASE_DIR}"
全局参数
参数名含义可选值默认值支持版本
nacos.home(-D)Nacos的根目录目录路径Nacos安装的目录>= 0.1.0
nacos.standalone(-D)是否在单机模式true/falsefalse>= 0.1.0
nacos.functionMode(-D)启动模式,支持只启动某一个模块,不设置时所有模块都会启动config/naming/空>= 0.9.0
nacos.inetutils.prefer-hostname-over-ipcluster.conf里是否应该填hostnametrue/falsefalse>= 0.3.0
nacos.inetutils.ip-address本机IP,该参数设置后,将会使用这个IP去cluster.conf里进行匹配,请确保这个IP的值在cluster.conf里是存在的本机IPnull>= 0.3.0
nacos.security.ignore.urls控制台鉴权跳过的接口需要跳过控制台鉴权的接口列表>= 0.9.0
Naming模块
参数名含义可选值默认值支持版本
nacos.naming.data.warmup是否在Server启动时进行数据预热true/falsefalse>= 1.0.2
nacos.naming.expireInstance是否自动摘除临时实例true/falsetrue>= 1.0.2
nacos.naming.distro.taskDispatchPeriod同步任务生成的周期,单位为毫秒正整数200>= 1.0.2
nacos.naming.distro.batchSyncKeyCount同步任务每批的key的数目正整数1000>= 1.0.2
nacos.naming.distro.syncRetryDelay同步任务失败的重试间隔,单位为毫秒正整数5000>= 1.0.2

除了上面列到的在application.properties里配置的属性,还有一些可以在运行时调用接口来进行调节,这些参数都在Open API里的查看系统当前数据指标这个API里有声明。

Config模块
参数名含义可选值默认值支持版本
db.num数据库数目正整数0>= 0.1.0
db.url.0第一个数据库的URL字符串>= 0.1.0
db.url.1第二个数据库的URL字符串>= 0.1.0
db.user数据库连接的用户名字符串>= 0.1.0
db.password数据库连接的密码字符串>= 0.1.0

当前数据库配置支持多数据源。通过db.num来指定数据源个数,db.url.index为对应的数据库的链接。db.user以及db.password没有设置index时,所有的链接都以db.userdb.password用作认证。如果不同数据源的用户名称或者用户密码不一样时,可以通过符号,来进行切割,或者指定db.user.index,db.user.password来设置对应数据库链接的用户或者密码。需要注意的是,当db.userdb.password没有指定下标时,因为当前机制会根据,进行切割。所以当用户名或者密码存在,时,会把,切割后前面的值当成最后的值进行认证,会导致认证失败。

CMDB模块
参数名含义可选值默认值支持版本
nacos.cmdb.loadDataAtStart是否打开CMDBtrue/falsefalse>= 0.7.0
nacos.cmdb.dumpTaskInterval全量dump的间隔,单位为秒正整数3600>= 0.7.0
nacos.cmdb.eventTaskInterval变更事件的拉取间隔,单位为秒正整数10>= 0.7.0
nacos.cmdb.labelTaskInterval标签集合的拉取间隔,单位为秒正整数300>= 0.7.0

Nacos Java Client

客户端的参数分为两种,一种是通过-D参数进行指定的配置,一种是构造客户端时,通过Properties对象指定的配置,以下没有带-D标注的都是通过Properties注入的配置。

通用参数
参数名含义可选值默认值支持版本
endpoint连接Nacos Server指定的连接点,可以参考文档域名>= 0.1.0
endpointPort连接Nacos Server指定的连接点端口,可以参考文档合法端口号>= 0.1.0
namespace命名空间的ID命名空间的IDconfig模块为空,naming模块为public>= 0.8.0
serverAddrNacos Server的地址列表,这个值的优先级比endpoint高ip:port,ip:port,…>= 0.1.0
nacos.logging.path(-D)客户端日志的目录目录路径用户根目录>= 0.1.0
Naming客户端
参数名含义可选值默认值支持版本
namingLoadCacheAtStart启动时是否优先读取本地缓存true/falsefalse>= 1.0.0
namingClientBeatThreadCount客户端心跳的线程池大小正整数机器的CPU数的一半>= 1.0.0
namingPollingThreadCount客户端定时轮询数据更新的线程池大小正整数机器的CPU数的一半>= 1.0.0
com.alibaba.nacos.naming.cache.dir(-D)客户端缓存目录目录路径{user.home}/nacos/naming>= 1.0.0
com.alibaba.nacos.naming.log.level(-D)Naming客户端的日志级别info,error,warn等info>= 1.0.0
com.alibaba.nacos.client.naming.tls.enable(-D)是否打开HTTPStrue/falsefalse>= 1.0.0

Config客户端

参数名含义可选值默认值支持版本
configLongPollTimeout(config.long-poll.timeout 1.0.1版本)长轮询的超时时间,单位为毫秒正整数30000>= 1.0.2
configRetryTime(config.retry.time 1.0.1版本)长轮询任务重试时间,单位为毫秒正整数2000>= 1.0.2
maxRetry长轮询的重试次数正整数3>= 1.0.2
enableRemoteSyncConfig监听器首次添加时拉取远端配置布尔值false>= 1.0.2
com.alibaba.nacos.config.log.level(-D)Config客户端的日志级别info,error,warn等info>= 1.0.0
JM.SNAPSHOT.PATH(-D)客户端缓存目录目录路径{user.home}/nacos/config>= 1.0.0

第十二章:Nacos 实时监控

参考 Nacos 监控手册

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值