SpringCloudAlibaba之Nacos

1、简介

        Nacos支持基于DNS和基于RPC的服务发现,服务端可以通过SDK或者Api进行服务注册,相应的服务消费者可以使用DNS或者Http查找的方式获取服务列表。Spring Cloud 服务注册中心的服务器很多,如 ZookeeperEurekaConsul 等。 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版本)或者希望共同学习,关注微信公众号:上了年纪的小男孩。后台回复相应技术名称/技术点即可获得。(本人学习宗旨:学会了就要免费分享)

  • 18
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Cloud Alibaba 是一个基于 Spring Cloud 的开源框架,用于构建分布式应用程序。Nacos 是一个开源的服务发现、配置管理和服务管理平台,可以帮助开发人员更好地管理和维护分布式应用程序。 要搭建 Spring Cloud AlibabaNacos,需要按照以下步骤进行操作: 1. 下载和安装 JDK 和 Maven。 2. 创建一个 Spring Boot 项目,并添加 Spring Cloud AlibabaNacos 的依赖。 3. 在 Nacos 中创建一个命名空间和一个服务。 4. 在 Spring Boot 项目中配置 Nacos 的地址和服务信息。 5. 编写代码并运行应用程序。 具体的步骤可以参考 Spring Cloud AlibabaNacos 的官方文档,或者参考其他相关的教程和资料。 ### 回答2: SpringCloudAlibaba是一款非常流行的分布式系统框架,它提供了一个非常方便的方式来搭建高可扩展的分布式应用程序。当使用SpringCloudAlibaba构建分布式应用程序时,我们常常需要使用Nacos作为服务注册中心和配置中心。本文将介绍如何使用SpringCloudAlibaba来搭建Nacos。 首先,我们需要在本地安装Nacos。 步骤如下: 1. 下载Nacos:https://github.com/alibaba/nacos/releases 2. 解压下载的文件,进入bin目录 3. 运行startup.cmd(如果是在Linux系统下,运行startup.sh) 当我们成功启动Nacos后,我们需要在我们的应用程序中添加Nacos的依赖项。可以在pom.xml文件中添加如下代码: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> ``` 这个依赖项将会自动添加Spring Cloud Nacos Discovery的类和配置。 接下来,我们需要为我们的应用程序添加Nacos配置。可以在application.properties或者application.yml文件中添加如下代码: ``` spring.cloud.nacos.discovery.server-addr=localhost:8848 ``` 当我们的应用程序启动时,它将会自动注册到Nacos。 最后,我们需要在我们的应用程序中使用Nacos作为配置中心。可以在配置文件中添加如下配置: ``` spring.cloud.nacos.config.server-addr=localhost:8848 ``` 这个配置项将会告诉我们的应用程序从Nacos中加载配置项。 当我们成功完成这些步骤后,我们的应用程序就已经成功地搭建了Nacos。现在我们可以使用Nacos作为服务注册中心和配置中心来管理我们的应用程序了。 ### 回答3: SpringCloudAlibaba是阿里巴巴团队推出的微服务框架,其中的nacos作为注册中心、配置中心以及服务发现组件,是使用SpringCloudAlibaba搭建微服务架构的重要组成部分。 下面是搭建nacos的详细步骤: 1.安装Java环境和Maven环境。在安装之前需要确保已经正确配置好Java和Maven的环境变量。 2.下载nacos的安装包。从nacos的官网中下载最新版的nacos安装包,解压缩到任意目录下。 3.启动nacos server。通过命令行进入nacos安装包所在的bin目录下,使用以下命令启动nacos: Linux/Unix/Mac: sh startup.sh –m standalone Windows: cmd startup.cmd 启动成功后通过访问http://localhost:8848/nacos/访问nacos的管理控制台,管理员账号和密码默认为nacos/nacos。 4.配置nacos客户端。在pom.xml文件中添加nacos的依赖: <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId> spring-cloud-starter-alibaba-nacos-discovery </artifactId> </dependency> 在配置文件application.yml中配置nacos信息: spring: cloud: nacos: discovery: server-addr: localhost:8848 # nacos服务的地址 application: name: service-provider # 微服务的名称 5.发布和发现微服务。使用@EnableDiscoveryClient注解启用服务发现功能,在微服务启动时自动注册到nacos中,nacos管理控制台会显示注册的微服务信息。其他微服务可以通过调用nacos的API或者使用Ribbon等工具进行服务发现。 至此,使用SpringCloudAlibaba搭建nacos的过程就结束了。nacos提供的服务注册、配置管理和服务发现功能,为微服务的构建和部署提供了更方便、更高效、更可靠的方案。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值