一、概述
Nacos /nɑ:k??s/ 是 Dynamic Na
ming and Co
nfiguration S
ervice的首字母簡稱,一個更易于構(gòu)建云原生應(yīng)用的動態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理平臺。
Nacos 致力于幫助您發(fā)現(xiàn)、配置和管理微服務(wù)。Nacos 提供了一組簡單易用的特性集,幫助您快速實(shí)現(xiàn)動態(tài)服務(wù)發(fā)現(xiàn)、服務(wù)配置、服務(wù)元數(shù)據(jù)及流量管理。
Nacos 幫助您更敏捷和容易地構(gòu)建、交付和管理微服務(wù)平臺。 Nacos 是構(gòu)建以“服務(wù)”為中心的現(xiàn)代應(yīng)用架構(gòu) (例如微服務(wù)范式、云原生范式) 的服務(wù)基礎(chǔ)設(shè)施。
- 版本說明;本教程基于如下版本
類別 | 版本 |
---|---|
spring boot | 2.6.7 |
spring-cloud | 2021.0.0 |
spring-cloud-alibaba | 2021.0.1.0 |
nacos | 2.1.1 |
- nacos官網(wǎng):home (nacos.io)
二、安裝
1、windows下單機(jī)安裝
1.1、下載
- 下載地址:https://github.com/alibaba/nacos/releases,推薦的穩(wěn)定版本為2.1.1
兩個壓縮包都可以。
1.2、解壓安裝
在安裝目錄下解壓
1.3、啟動
進(jìn)入bin目錄,cmd命令啟動 startup
nacos默認(rèn)是集群模式,如果要單機(jī)啟動,需加上參數(shù) -m standalone
1.4、訪問
默認(rèn)端口 8848
,訪問路徑 localhost:8848/nacos
,默認(rèn)賬號nacos
,默認(rèn)密碼 nacos
2、windows下集群安裝
單機(jī)windows下部署3個節(jié)點(diǎn)
2.1、節(jié)點(diǎn)目錄
把nacos壓縮包解壓至3個安裝目錄,即節(jié)點(diǎn)目錄;分別為:node_8848
、node_8858
、node_8868
每個目錄下都是一個nacos
2.2、集群配置
分別進(jìn)入每個節(jié)點(diǎn)的 conf
目錄
- application.properties
打開
application.properties
,分別修改節(jié)點(diǎn)的端口,數(shù)據(jù)庫等。
每個節(jié)點(diǎn)的端口不同,分別為:8848
、8858
、8868
三個節(jié)點(diǎn)的數(shù)據(jù)庫配置信息一致,都連接同一個數(shù)據(jù)庫。
- cluster.conf
修改
cluster.conf.example
文件為cluster.conf
;修改文件中的節(jié)點(diǎn)地址和端口
三個節(jié)點(diǎn)中,只有 application.properties
中的端口不同,其余配置都一樣
2.3、創(chuàng)建數(shù)據(jù)庫
用 conf
目錄下的建表腳本文件 nacos-mysql.sql
創(chuàng)建數(shù)據(jù)表
2.4、啟動測試
進(jìn)入每個節(jié)點(diǎn)下的 bin
,使用 cmd
命令,啟動 startup
,不用加參數(shù)
3、Docker Compose中安裝部署
前提:有 Docker Compose 運(yùn)行環(huán)境
3.1、docker-compose.yml
version: "3.9"
services:
# nacos服務(wù)
nacos-server:
# 鏡像
image: nacos/nacos-server:v2.1.1
# 容器名稱
container_name: c-nacos-server
# 啟動環(huán)境
environment:
# 單機(jī)模式
- MODE=standalone
# 內(nèi)存
- JVM_XMS=512m
- JVM_XMX=512m
- JVM_XMN=256m
# 時區(qū)
- TZ=Asia/Shanghai
# 數(shù)據(jù)掛載點(diǎn)
# 宿主機(jī)目錄 : nacos容器內(nèi)目錄
volumes:
# 日志
- ../services/nacos-server/volumes/log:/home/nacos/logs
# 配置
- ../services/nacos-server/volumes/conf:/home/nacos/conf
ports:
- 8848:8848
# 添加健康檢測
healthcheck:
test: ["CMD", "curl" ,"-f", "localhost:8848/nacos"]
# 健康檢查間隔時間:默認(rèn)為 30 秒
interval: 30s
# 健康檢查命令運(yùn)行超時時間;超過這個時間,本次健康檢查就被視為失敗
timeout: 3s
# 當(dāng)連續(xù)失敗指定次數(shù)后,則將容器狀態(tài)視為 unhealthy
retries: 5
# 20s:表示啟動后的20s,作為啟動時間;
# 這個時間段的健康檢測,不計入統(tǒng)計次數(shù),但仍會發(fā)生檢測
start_period: 20s
# 依賴
#depends_on:
# 依賴于數(shù)據(jù)庫服務(wù)
#db-server:
# 服務(wù)健康監(jiān)視器:當(dāng)被依賴服務(wù)健康時本服務(wù)才會啟動
#condition: service_healthy
# condition: service_started
# 用來給容器root權(quán)限
privileged: true
# 重啟(由compose的開機(jī)自啟來控制每個容器的啟動)
# restart: always
# 容器啟動后,如果處于空閑狀態(tài),會自動退出
# 相當(dāng)于 -it;可以讓容器一直運(yùn)行
tty: true
stdin_open: true
# 加入網(wǎng)絡(luò)
#networks:
# 隨機(jī)ip
#- inner-net
3.2、application.properties
放在掛載目錄
conf
下面
#
# Copyright 1999-2021 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
### Include message field
server.error.include-message=ON_PARAM
### Default web server port:
server.port=8848
# 設(shè)置 housekeeper 線程數(shù)量
nacos.core.thread.count=5
#*************** 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://localhost:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=nacos
db.password.0=nacos
### 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 ***************#
### Data dispatch task execution period in milliseconds: Will removed on v2.1.X, replace with nacos.core.protocol.distro.data.sync.delayMs
# nacos.naming.distro.taskDispatchPeriod=200
### Data count of batch sync task: Will removed on v2.1.X. Deprecated
# nacos.naming.distro.batchSyncKeyCount=1000
### Retry delay in milliseconds if sync task failed: Will removed on v2.1.X, replace with nacos.core.protocol.distro.data.sync.retryDelayMs
# 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
### will be removed and replaced by `nacos.naming.clean` properties
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
### 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, is deprecated in 1.2.0:
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
### 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=true
### 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=serverIdentity
nacos.core.auth.server.identity.value=security
### worked when nacos.core.auth.system.type=nacos
### The token expiration in seconds:
nacos.core.auth.plugin.nacos.token.expire.seconds=18000
### The default token:
nacos.core.auth.plugin.nacos.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789
### 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
#*************** 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
3.3、nacos-logback.xml
放在掛載目錄
conf
下面
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="1 seconds">
<contextName>logback</contextName>
<!-- 日志文件路徑 -->
<property name="logPath" value="/home/nacos/logs/"></property>
<!-- 日志文件名稱 -->
<property name="logName" value="nacos_log"></property>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在記錄的日志文檔的路徑及文檔名 -->
<file>${logPath}${logName}.log</file>
<!--日志文檔輸出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level --- [%thread] %logger Line:%-3L - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志記錄器的滾動策略,按日期,按大小記錄 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志歸檔 -->
<fileNamePattern>${logPath}/%d{yyyy-MM-dd}/${logName}_%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文檔保留天數(shù)-->
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>
<root level="debug">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
<logger name="com.example.logback" level="warn" />
</configuration>
三、配置管理
1、父工程pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuwer</groupId>
<artifactId>nacos</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
<!-- 子模塊 -->
<module>config</module>
</modules>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<!-- 編譯編碼 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!--管理jar包的版本,讓子項(xiàng)目中引用一個依賴而不用顯式的列出版本號-->
<dependencyManagement>
<dependencies>
<!--spring-cloud-dependencies-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2021.0.1.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
2、子工程pom
需要從nacos中引入配置的模塊
- 加入
spring-cloud-starter-alibaba-nacos-config
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>nacos</artifactId>
<groupId>com.tuwer</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>config</artifactId>
<description>配置管理</description>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>
</project>
3、nacos配置文件
主要配置一些不太穩(wěn)定,容易發(fā)生變化的內(nèi)容;
如:服務(wù)運(yùn)行中需要調(diào)用的一些參數(shù),對象的屬性、系統(tǒng)常量等;
共添加3個:1個主配置文件,2個共享配置文件
內(nèi)容分別為:
4、bootstrap.properties
主要配置一些相對穩(wěn)定,不易變化的內(nèi)容;
如:模塊名稱、端口、服務(wù)地址、其它配置文件名稱等
# nacos服務(wù)地址
spring.cloud.nacos.server-addr=localhost:8848
# ############ 應(yīng)用名稱(主配置文件) ############
# 默認(rèn)去調(diào)用和應(yīng)用名稱相同的配置文件(主配置文件)
# ### 優(yōu)先級:
# ### test-dev.properties
# ### test.properties
# ### test
spring.application.name=config
# ################ 其它配置文件 ################
# shared 和 extension 效果一樣,都是引入其它配置
# shared 表示共享;其它服務(wù)也可能會用到的配置
# extension 表示擴(kuò)展;本服務(wù)特有的
# 編號從0開始
# data-id 和配置中的文件名完全一致(如果有擴(kuò)展名,不能省略)
spring.cloud.nacos.config.shared-configs[0].data-id=common.yml
spring.cloud.nacos.config.shared-configs[0].refresh=true
spring.cloud.nacos.config.shared-configs[1].data-id=test.yml
spring.cloud.nacos.config.shared-configs[1].refresh=true
#spring.cloud.nacos.config.extension-configs[0].data-id=common.yml
#spring.cloud.nacos.config.extension-configs[1].data-id=test.yml
5、啟動類與Controller
- 啟動類
@SpringBootApplication
public class BootApp {
public static void main(String[] args) {
SpringApplication.run(BootApp.class, args);
}
}
- Controller
@RestController
@RefreshScope
public class TestController {
@Value("${name}")
private String name;
@Value("${url}")
private String url;
@Value("${addr}")
private String addr;
@GetMapping("/test")
public String name() {
return name + " : " + url + " : " + addr;
}
}
6、自動刷新
-
@RefreshScope
:在需要引用配置文件的類上添加該注解 - 如果模塊中除主配置文件外,還引入了其它配置文件,還要設(shè)置其它配置文件的
refresh
值為true
-
最佳實(shí)踐:把模塊中所有的配置項(xiàng)集中到一個類中(bean),類上添加
@RefreshScope
注解,每個配置項(xiàng)提供get
方法,把該類注入到需要引用配置文件的類中,調(diào)用get方法獲取值。
7、測試
四、服務(wù)注冊
在父工程下新建服務(wù)提供者模塊:provider
1、引入依賴
- 服務(wù)注冊與發(fā)現(xiàn)
spring-cloud-starter-alibaba-nacos-discovery
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
2、bootstrap.properties
如果是nacos集群,server-addr應(yīng)該把每個節(jié)點(diǎn)都加上,或者使用 nginx 地址,負(fù)載每個節(jié)點(diǎn);服務(wù)發(fā)現(xiàn)也是同樣的配置。
# nacos服務(wù)地址(兩種方式都可以)
#spring.cloud.nacos.server-addr=localhost:8848
spring.cloud.nacos.discovery.server-addr=localhost:8848
# ############ 應(yīng)用名稱 ############
spring.application.name=provider
3、服務(wù)接口
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
return "測試";
}
}
4、啟動類
@SpringBootApplication
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class, args);
}
}
5、測試
服務(wù)啟動后可以在nacos工作臺查看注冊的服務(wù)
五、服務(wù)發(fā)現(xiàn)
在父工程下新建服務(wù)消費(fèi)者模塊:consumer
1、引入依賴
- 服務(wù)注冊與發(fā)現(xiàn)
spring-cloud-starter-alibaba-nacos-discovery
- 負(fù)載均衡
spring-cloud-starter-loadbalancer
,在SpringColud2021.0.0
中不使用netflix了,所以不用Ribbon來實(shí)現(xiàn)負(fù)載均衡,用Spring Cloud Loadbalancer
來替代 Ribbon
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
</dependencies>
2、bootstrap.properties
# 指定端口,避免與提供者沖突
server.port=8000
# nacos服務(wù)地址
spring.cloud.nacos.server-addr=localhost:8848
#spring.cloud.nacos.discovery.server-addr=localhost:8848
# ############ 應(yīng)用名稱 ############
spring.application.name=consumer
3、啟動類
@SpringBootApplication
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class, args);
}
}
4、配置 RestTemplate
要加上
@LoadBalanced
@Configuration
public class MyConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
5、調(diào)用服務(wù)
@RestController
public class ConsumerController {
@Resource
private RestTemplate restTemplate;
@GetMapping("/t")
public String test(){
return restTemplate.getForObject("http://provider/test", String.class);
}
}
6、測試
六、高級特性
1、臨時實(shí)例與持久實(shí)例
1> 臨時實(shí)例
默認(rèn)情況下,注冊給nacos的實(shí)例都是臨時實(shí)例。
臨時實(shí)例會通過客戶端和服務(wù)端之間的心跳來?;?。
默認(rèn)情況下,客戶端會每隔 5秒
發(fā)送一次心跳。如果服務(wù)端超過 15秒
沒有收到客戶端的心跳,就會把該實(shí)例標(biāo)記為不健康狀態(tài),超過 30秒
沒有收到心跳,會就刪除實(shí)例。
臨時實(shí)例在服務(wù)下線后會被刪除。
2> 持久實(shí)例
設(shè)置持久實(shí)例:spring.cloud.nacos.discovery.ephemeral=false
ephemeral:臨時的,短暫的。
持久實(shí)例在服務(wù)下線后不會刪除,變?yōu)椴唤】禒顟B(tài)。
2、保護(hù)閾值
保護(hù)閾值:可以設(shè)置為 0~1
之間的浮點(diǎn)數(shù),它其實(shí)是?個?例值(當(dāng)前服務(wù)健康實(shí)例數(shù)/總實(shí)例數(shù))。
?般流程下, nacos是服務(wù)注冊中?,服務(wù)消費(fèi)者要從nacos獲取某?個服務(wù)的可?實(shí)例信息,對于服務(wù)實(shí)例有健康/不健康狀態(tài)之分, nacos在返回給消費(fèi)者實(shí)例信息的時候,會返回健康實(shí)例。這個時候在?些?并發(fā)、?流量場景下會存在?定的問題。
如:服務(wù)A有100個實(shí)例, 98個實(shí)例都不健康了,只有2個實(shí)例是健康的,如果nacos只返回這兩個健康實(shí)例的話,那么后續(xù)消費(fèi)者的請求將全部被分配到這兩個實(shí)例,流量洪峰到來, 2個健康的實(shí)例也扛不住了,整個服務(wù)A 就扛不住,上游的微服務(wù)也會導(dǎo)致崩潰,產(chǎn)?雪崩效應(yīng)。
保護(hù)閾值的意義在于當(dāng)服務(wù)A健康實(shí)例數(shù)/總實(shí)例數(shù) < 保護(hù)閾值 的時候,說明健康實(shí)例真的不多了,這個時候保護(hù)閾值會被觸發(fā)(狀態(tài)true)。nacos將會把該服務(wù)所有的實(shí)例信息(健康的+不健康的)全部提供給消費(fèi)者,消費(fèi)者可能訪問到不健康的實(shí)例,請求失敗,但這樣也?造成雪崩要好,犧牲了?些請求,保證了整個系統(tǒng)的可用性。
3、權(quán)重NacosRule
在SpringColud2021.0.0
中不使用netflix了,不用Ribbon來實(shí)現(xiàn)負(fù)載均衡。NacosRule 是Ribbon的擴(kuò)展,也就不提供了。權(quán)重也此版本中也沒有用了。
4、Cluster就近訪問
2021.0.1.0
版本中無效
七、常見問題
1、NacosException
Could not find leader
com.alibaba.nacos.api.exception.NacosException: failed to req API:/nacos/v1/ns/instance after all servers([docker-nacos-server:8848]) tried: ErrCode:500, ErrMsg:caused: java.util.concurrent.ExecutionException: com.alibaba.nacos.consistency.exception.ConsistencyException: Could not find leader : naming_persistent_service_v2;caused: com.alibaba.nacos.consistency.exception.ConsistencyException: Could not find leader : naming_persistent_service_v2;caused: Could not find leader : naming_persistent_service_v2;
解決方案:
- 刪掉nacos文件夾下的data文件夾,重新啟動
- 如果是
docker
中安裝,刪除鏡像,重新啟動
2、gataway整合nacos
通過gateway訪問nacos,gateway中需要加入spring-cloud-starter-loadbalancer
依賴文章來源:http://www.zghlxwxcb.cn/news/detail-775967.html
參考自:https://www.bilibili.com/video/BV1q3411Z79z文章來源地址http://www.zghlxwxcb.cn/news/detail-775967.html
到了這里,關(guān)于Nacos的安裝與使用(SpringCloud)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!