SpringCloudAlibaba之Nacos
1、简介
????????Nacos支持基于DNS和基于RPC的服务发现,服务端可以通过SDK或者Api进行服务注册,相应的服务消费者可以使用DNS或者Http查找的方式获取服务列表。Spring Cloud 服务注册中心的服务器很多,如 Zookeeper、Eureka、Consul 等。 Spring Cloud Alibaba 中使用的注册中心为 Alibaba 的中间件 Nacos。
2、下载
下载地址:https://github.com/alibaba/nacos/releases
2、启动
2.1、单机启动
下载解压后运行。
# 1、进入bin目录
startup.cmd -m standalone # windows系统
startup.sh -m standalone # linux系统
2.2、使用外部数据源
使用mysql数据库,外部数据源初始化。
# 1、在conf目录下有sql初始化脚本
mysql -uroot -p # 登录数据库
create database nacos; # 创建数据库
use nacos; # 使用nacos数据库
source **/mysql-schema.sql # 初始化sql文件
?配置文件中配置使用外部数据源
#*************** Config Module Related Configurations ***************#
# spring.datasource.platform=mysql # 此方式也过期
# 使用外部数据源配置
spring.sql.init.platform=mysql # 新版设置数据库服务类型方式
### Count of DB:
db.num=1
### Connect URL of DB:
db.url.0=jdbc:mysql://localhost:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=146815
### Connection pool configuration: hikariCP
db.pool.config.connectionTimeout=30000
db.pool.config.validationTimeout=10000
db.pool.config.maximumPoolSize=20
db.pool.config.minimumIdle=2
2.3、配置文件详解(application.properties )
#*************** Spring Boot Related Configurations ***************#
### Default web context path:
server.servlet.contextPath=/nacos
### Include message field
server.error.include-message=ALWAYS
### 默认端口号
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:
### Deprecated configuration property, it is recommended to use `spring.sql.init.platform` replaced.
# spring.datasource.platform=mysql # 此方式也过期
# 使用外部数据源配置
spring.sql.init.platform=mysql # 新版设置数据库服务类型方式
### Count of DB:
db.num=1
### Connect URL of DB:
db.url.0=jdbc:mysql://localhost:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=146815
### Connection pool configuration: hikariCP
db.pool.config.connectionTimeout=30000
db.pool.config.validationTimeout=10000
db.pool.config.maximumPoolSize=20
db.pool.config.minimumIdle=2
#*************** Naming Module Related Configurations ***************#
### 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
### Add in 2.0.0
### The interval to clean empty service, unit: milliseconds.
# nacos.naming.clean.empty-service.interval=60000
### The expired time to clean empty service, unit: milliseconds.
# nacos.naming.clean.empty-service.expired-time=60000
### The interval to clean expired metadata, unit: milliseconds.
# nacos.naming.clean.expired-metadata.interval=5000
### The expired time to clean metadata, unit: milliseconds.
# nacos.naming.clean.expired-metadata.expired-time=60000
### The delay time before push task to execute from service changed, unit: milliseconds.
# nacos.naming.push.pushTaskDelay=500
### The timeout for push task execute, unit: milliseconds.
# nacos.naming.push.pushTaskTimeout=5000
### The delay time for retrying failed push task, unit: milliseconds.
# nacos.naming.push.pushTaskRetryDelay=1000
### Since 2.0.3
### The expired time for inactive client, unit: milliseconds.
# nacos.naming.client.expired.time=180000
#*************** 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=file:.
#*************** 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
nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**
### The auth system to use, currently only 'nacos' and 'ldap' is supported:
nacos.core.auth.system.type=nacos
#从 nacos2.2.0.1 版本开始,nacos 配置文件中去掉了默认的鉴权配置,需要用户手工添加,否则无法启动 nacos。(注:nacos.core.auth.*相关配置。
### If turn on auth system:
nacos.core.auth.enabled=false
### 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=false
### Since 1.4.1, Turn on/off white auth for user-agent: nacos-server, only for upgrade from old version.
nacos.core.auth.enable.userAgentAuthWhite=false
### Since 1.4.1, worked when nacos.core.auth.enabled=true and nacos.core.auth.enable.userAgentAuthWhite=false.
### The two properties is the white list for auth and used by identity the request from other server.
nacos.core.auth.server.identity.key=xxx
nacos.core.auth.server.identity.value=ccc
### worked when nacos.core.auth.system.type=nacos
### The token expiration in seconds:
nacos.core.auth.plugin.nacos.token.cache.enable=false
nacos.core.auth.plugin.nacos.token.expire.seconds=18000
### The default token (Base64 String):
nacos.core.auth.plugin.nacos.token.secret.key=adadafaffafafefefefefewdqwdwefe089989=
### worked when nacos.core.auth.system.type=ldap,{0} is Placeholder,replace login username
#nacos.core.auth.ldap.url=ldap://localhost:389
#nacos.core.auth.ldap.basedc=dc=example,dc=org
#nacos.core.auth.ldap.userDn=cn=admin,${nacos.core.auth.ldap.basedc}
#nacos.core.auth.ldap.password=admin
#nacos.core.auth.ldap.userdn=cn={0},dc=example,dc=org
#nacos.core.auth.ldap.filter.prefix=uid
#nacos.core.auth.ldap.case.sensitive=true
#*************** Istio Related Configurations ***************#
### If turn on the MCP server:
nacos.istio.mcp.server.enabled=false
#*************** 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
#*************** Distro Related Configurations ***************#
### Distro data sync delay time, when sync task delayed, task will be merged for same data key. Default 1 second.
# nacos.core.protocol.distro.data.sync.delayMs=1000
### Distro data sync timeout for one sync data, default 3 seconds.
# nacos.core.protocol.distro.data.sync.timeoutMs=3000
### Distro data sync retry delay time when sync data failed or timeout, same behavior with delayMs, default 3 seconds.
# nacos.core.protocol.distro.data.sync.retryDelayMs=3000
### Distro data verify interval time, verify synced data whether expired for a interval. Default 5 seconds.
# nacos.core.protocol.distro.data.verify.intervalMs=5000
### Distro data verify timeout for one verify, default 3 seconds.
# nacos.core.protocol.distro.data.verify.timeoutMs=3000
### Distro data load retry delay when load snapshot data failed, default 30 seconds.
# nacos.core.protocol.distro.data.load.retryDelayMs=30000
### enable to support prometheus service discovery
#nacos.prometheus.metrics.enabled=true
### Since 2.3
#*************** Grpc Configurations ***************#
## sdk grpc(between nacos server and client) configuration
## Sets the maximum message size allowed to be received on the server.
#nacos.remote.server.grpc.sdk.max-inbound-message-size=10485760
## Sets the time(milliseconds) without read activity before sending a keepalive ping. The typical default is two hours.
#nacos.remote.server.grpc.sdk.keep-alive-time=7200000
## Sets a time(milliseconds) waiting for read activity after sending a keepalive ping. Defaults to 20 seconds.
#nacos.remote.server.grpc.sdk.keep-alive-timeout=20000
## Sets a time(milliseconds) that specify the most aggressive keep-alive time clients are permitted to configure. The typical default is 5 minutes
#nacos.remote.server.grpc.sdk.permit-keep-alive-time=300000
## cluster grpc(inside the nacos server) configuration
#nacos.remote.server.grpc.cluster.max-inbound-message-size=10485760
## Sets the time(milliseconds) without read activity before sending a keepalive ping. The typical default is two hours.
#nacos.remote.server.grpc.cluster.keep-alive-time=7200000
## Sets a time(milliseconds) waiting for read activity after sending a keepalive ping. Defaults to 20 seconds.
#nacos.remote.server.grpc.cluster.keep-alive-timeout=20000
## Sets a time(milliseconds) that specify the most aggressive keep-alive time clients are permitted to configure. The typical default is 5 minutes
#nacos.remote.server.grpc.cluster.permit-keep-alive-time=300000
注:从 nacos2.2.0.1 版本开始,nacos 配置文件中去掉了默认的鉴权配置,需要用户手工添加,否则无法启动 nacos。
nacos.core.auth.* # 相关配置参数
2.4、集群配置(cluster.conf)
#it is ip
#example
192.168.16.101:8848
192.168.16.102:8848
192.168.16.103:8848
注:集群启动使用命令(默认是使用cluster模式启动的):startup.cmd/startup.sh。
2.5、微服务使用nacos集群作为注册中心配置
spring:
application:
name: consumer-default-8084
cloud:
nacos:
discovery:
# nacos 集群模式下服务配置,使用逗号隔开
server-addr: ip1:8848,ip2:8848,ip3:8848
3、注册中心使用案例
微服务使用nacos作为注册中心使用
3.1、添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
3.2、服务配置nacos信息
spring:
application:
name: consumer-openfeign-8084
cloud:
nacos:
discovery:
server-addr: localhost:8848
# 配置临时实例还是持久实例:true 为临时实例,false 为持久实例。
ephemeral: true # 默认值为true
group: weilong # 指定当前微服务属于的namespace、group
namespace: fkasjfkasjsj # 想同namespace和group下的微服务才能相互调用
# 如果配置鉴权需要配置用户名和密码
username: nacos
password: nacos
注:临时实例与持久实例的实例存储的位置与健康检测机制是不同的。
1、临时实例:默认情况。服务实例仅会注册在 Nacos 内存,不会持久化到 Nacos 磁盘。其健康检测机制为 Client 模式,即 Client 主动向 Server 上报其健康状态。默认心跳间隔为5 秒。在 15 秒内 Server 未收到 Client 心跳,则会将其标记为“不健康”状态;在 30 秒内若收到了 Client 心跳,则重新恢复“健康”状态,否则该实例将从 Server 端内存清除。
2、持久实例:服务实例不仅会注册到 Nacos 内存,同时也会被持久化到 Nacos 磁盘。其健康检测机制为 Server 模式,即 Server 会主动去检测 Client 的健康状态,默认每 20 秒检测一次。健康检测失败后服务实例会被标记为“不健康”状态,但不会被清除,因为其是持久化在磁盘的。
3.3、主启动类
@SpringBootApplication
@EnableDiscoveryClient // 此注解在nacos2.2.1版本以后可以省略
public class ApplicationConsumer8082 {
public static void main(String[] args) {
SpringApplication.run(ApplicationConsumer8082.class, args);
}
}
4、配置中心
微服务使用nacos作为配置中心使用
4.1、添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
4.2、服务配置使用nacos作为配置中心的配置
spring:
config:
# 表明使用配置中心的dataid名称
import:
- optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
application:
name: provider-nacos-config
cloud:
nacos:
# discovery:
# server-addr: localhost:8848
# group: weilong
config: # 配置中心信息
server-addr: localhost:8848
file-extension: yml # 配置中心配置文件类型
namespace: adafafaf # 指定配置文件所属的namespace和group
group: weilong
prefix: provider-nacos-config
# 如果配置鉴权需要配置用户名和密码
username: nacos
password: nacos
profiles: # 选择当前使用环境
active: dev
4.3、使用动态刷新
@RestController
@RequestMapping("/provider01")
@RefreshScope // 开启nacos动态配置刷新功能
public class RestTestController {
@Value("${test.name}")
private String name;
@Autowired
private DepartService departService;
@GetMapping("/test")
public String test(){
return "hello provider01" + name;
}
}
4.4、配置中心dataId命名规则
dataId组成格式:
${prefix}-${spring.profiles.active}.${file-extension}
##注:
# 1、prefix默认值为spring.application.name的值,可以通过spring.cloud.nacos.config.prefix进行覆盖
# 2、spring.profiles.active不存在时,连接符'-'也不存在
# 3、file-extension可以通过spring.cloud.nacos.config.file-extension配置
4.5、共享配置、扩展配置和应用配置
????????共享配置,扩展配置,当前服务配置。若在三个配置中具有相同属性设置,但它们具有不同的值,那么,后加载的会将先加载的给覆盖。即这三类配置的优先级由低到高是:共享配置,扩展配置,当前服务配置 。
spring:
config:
# 表明使用配置中心的dataid名称
import:
- optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
application:
name: provider-nacos-config
cloud:
nacos:
config: # 配置中心信息
server-addr: localhost:8848
file-extension: yml # 配置中心配置文件类型
# 同一个group中的不同服务可以共享
shared-configs:
data-id: ***.yml
refresh: true
# 不同group中不同服务共享
extension-configs:
data-id: ***.yml
refresh: true
5、动态刷新配置原理
????????Nacos Config Server 中配置数据的变更,Nacos Config Client 是如何知道的呢?Nacos 采用的是长轮询模型。长轮询模型整合了 Push 与 Pull 模型的优势。Client 仍定时发起 Pull 请求,查看 Server端数据是否更新。若发生了更新,则 Server 立即将更新数据以响应的形式 Push 给 Client 端;若没有发生更新,Server 端并不向 Client 进行 Push,而是临时性的保持住这个连接一段时间。若在此时间段内,Server 端数据发生了变更,则立即将变更数据 Push 给 Client。若仍未发生变更,则放弃这个连接。等待着下一次 Client 的 Pull 请求。长轮询模型,是 Push 与 Pull 模型的整合,既降低了 Push 模型中长连接的维护问题,又降低了 Push 模型实时性较低的问题。
总结:本文介绍nacos作为配置中心和注册中心的使用,同时介绍了nacos集群和如何使用外部数据源的配置,并且进行案例演示,帮助大家快速入门nacos的使用。
????????本人是一个从小白自学计算机技术,对运维、后端、各种中间件技术、大数据等有一定的学习心得,想获取自学总结资料(pdf版本)或者希望共同学习,关注微信公众号:上了年纪的小男孩。后台回复相应技术名称/技术点即可获得。(本人学习宗旨:学会了就要免费分享)
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!