前言
spring-cloud集成nacos,必须先在本地或者服务器安装nacos客户端
一:nacos环境搭建以及服务启动
1.环境准备:
2.下载源码或者安装包,笔者为了方便下了安装包,下面就以安装包的方式记录,其实大同小异,无非是代码更加直观一些。
安装包下载地址:github.com/alibaba/nac…
这个是nacos解压下后的目录结构。
3.启动Nacos服务前的准备工作!!!不然直接启动你会发现报错报错报错!
- 在本地创建nacos数据库,执行conf/mysql-schema.sql脚本。这个是为集群配置做准备的,不然会报数据库为null异常。
- 修改conf/appplication.properties文件
在nacos安装目录新建plugins/mysql文件目录,把mysql-connector-java的(注意对应mysql版本)的jar包丢进去,否则会报数据库链接异常 。 附上maven仓库jar包地址
4.启动Nacos服务
可以通过命令或者直接点击相应的startup文件,启动默认是集群启动!
这里先单机启动Nacos,启动如果报错详细查看步骤3!
Linux启动命令(standalone表示单机启动):sh startup.sh -m standalone
windows启动命令 : startup.cmd -m standalone
window11可以在对应目录打开终端,否则需要切换到对应目录
启动成功后如下,打开http://192.168.3.51:8848/nacos/index.html
5.集群启动Nacos服务
我这里为了方便就在本地启动集群了,真实情况肯定不会在windows本地,操作简单粗暴,直接复制nacos,像这样复制2份(为什么是2份,因为内存不允许玩的花)。
重点是修改上面提到的application.properties文件里的端口号,集群用的是同一个数据库,所以mysql链接不用修改。然后复制一份cluster.conf.example文件,命名为cluster.conf,这个是集群的配置。
修改配置如下:
但是这里有个坑,我到现在还没有解决,我启动了8848的服务之后,如果想启动8849端口就提示我端口已经被占用了,但是我调用命令查看8849端口的使用情况却发现它被8848的服务占用了,无奈之下只能改用其它端口。
之后就是依次启动,启动成功之后就是这样的:
如果发现第一行The server IP list of Nacos is[],就是没有配置集群列表
这里也挺奇怪,网上查也没有查到结果,上面只配置了本地的端口,莫名的结尾加上了21网段的8848端口,再次查看集群的配置文件发现也多了这个配置。一脸疑惑!!
登录nacos就能在集群管理里看到节点,UP表示开启,DOWN表示关闭
结尾:
到这里Nacos服务就准备就绪了,下面开始Nacos服务的注册发现!
docker部署nacos
拉取 Nacos 镜像文件
docker pull nacos/nacos-server:v2.2.3
启动 Nacos 容器
步骤 1:创建容器网络
docker network create nacos_network
步骤 2:创建挂载数据卷文件夹
mkdir -p /usr/local/docker/nacos/logs
mkdir -p /usr/local/docker/nacos/conf
步骤 3:在conf文件夹中创建application.properties 用来映射Nacos配置文件
touch application.properties
步骤 4.在application.properties中添加配置信息(点击获取)
#
# 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=ALWAYS
### 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 ***************#
### Deprecated configuration property, it is recommended to use `spring.sql.init.platform` replaced.
#spring.datasource.platform=${SPRING_DATASOURCE_PLATFORM:}
spring.sql.init.platform=${SPRING_DATASOURCE_PLATFORM:}
# nacos.plugin.datasource.log.enabled=true
### Count of DB:
db.num=1
### Connect URL of DB:
db.url.0=jdbc:mysql://mysql:3306/nacos_devtest?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
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:
### 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
### accesslog automatic cleaning time
server.tomcat.accesslog.max-days=30
### 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 (Base64 string):
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
#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
###*************** 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
#*************** 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
步骤 5.修改application.properties配置信息
将mysql连接信息配置成自己的
步骤 6:启动 Nacos 容器
docker run --name nacos \
-e MODE=standalone \
-v /usr/local/docker/nacos/conf/application.properties:/home/nacos/conf/application.properties \
-v /usr/local/docker/nacos/logs:/home/nacos/logs \
-p 8848:8848 -d \
-p 9848:9848 \
--restart always nacos/nacos-server:v2.2.3
备注:
- 使用docker安装的nacos服务,2.x版本后增加了 grpc 通信并且增加nacos的集群端口上下偏移1000,创建容器时除了
8848还需要把9848也暴露出来。如:-p 8848:8848 -p 9848:98489849和7848端口为服务端之间的通信端口,请勿暴露到外部网络环境和客户端测
| 端口 | 与主端口的偏移量 | 描述 |
|---|---|---|
| 8848 | 0 | 主端口,客户端、控制台及OpenAPI所使用的HTTP端口 |
| 9848 | 1000 | 客户端gRPC请求服务端端口,用于客户端向服务端发起连接和请求 |
| 9849 | 1001 | 服务端gRPC请求服务端端口,用于服务间同步等 |
| 7848 | -1000 | Jraft请求服务端端口,用于处理服务端间的Raft相关请求 |
步骤 7:访问 Nacos Web 控制台
启动完 Nacos 容器后,就可以通过 http://localhost:8848/nacos 访问 Nacos Web 控制台了。在控制台上,可以进行服务注册、配置管理和服务发现等操作。
开启登录
- 进入
/usr/local/docker/nacos/conf目录
cd /usr/local/docker/nacos/conf
- 编辑
application.properties,修改如下内容
### If turn on auth system:
nacos.core.auth.enabled=true
### The two properties is the white list for auth and used by identity the request from other server.
# nacos的登录username
nacos.core.auth.server.identity.key=nacos
# nacos的登录password
nacos.core.auth.server.identity.value=nacos
- 刷新页面,如下,需要登录了,用户名和密码就是上面配置的
开机自启动
- 新建
/etc/systemd/system/nacos.service
vi /etc/systemd/system/nacos.service
nacos.service的内容如下:
[Unit]
Description=nacos
After=network.target
[Service]
Type=forking
User=root
Group=root
ExecStart=/opt/nacos/bin/startup.sh -m standalone
ExecStop=/opt/nacos/bin/shutdown.sh
Environment="JAVA_HOME=/opt/jdk-11"
PrivateTmp=true
Restart=always
RestartSec=10
TimeoutSec=360
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
- 启动nacos,并开启开机自启动
systemctl start nacos
systemctl status nacos
systemctl enable nacos