nacos入门使用
前言
在当前微服务火爆的今天,在zookeeper,spring cloud,nacos选型之后,决定使用nacos作为微服务注册和管理的方案。因此从本文开始,介绍ncos的基本使用。
另nacos作为阿里巴巴提供的服务,中文文档是有提供,建议以官方文档为主。因为阅读文档时发现有部分描述不清晰,因此便有本文。
本文以SpringBoot和Nacos框架,linux为环境示例分别讲述nacos服务创建,nacos配置发布,nacos服务发布和管理。
正文
nacos服务创建
-
下载nacos release包
放入服务器目录下,解压压缩包
[root@VM-0-4-centos download]# tar -zxvf nacos-server-2.0.0-BETA.tar.gz
阅读一下重要目录
-
了解nacos目录
可以看到解压包里结构,重要的分别是bin文件和conf文件,分别对应启动脚本和配置文件
因此启动时,在bin文件夹内执行
[root@VM-0-4-centos bin]# sh startup.sh [root@VM-0-4-centos bin]# sh shutdown.sh
分别对应启动和关闭nacos服务。
再看看配置文件中的内容
# # 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:p 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.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: # 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 ### Add in 2.0.0 ### The interval to clean empty service # nacos.naming.clean.empty-service.interval=60000 ### The expired time to clean empty service # nacos.naming.clean.empty-service.expired-time=60000 ### The interval to clean expired metadata # nacos.naming.clean.expired-metadata.interval=5000 ### The expired time to clean metadata # nacos.naming.clean.expired-metadata.expired-time=60000 #*************** 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-ui/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 ### 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=true ### 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= nacos.core.auth.server.identity.value= #*************** 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
可以看到配置还是非常清晰的。如果想更换nacos端口,更改server.port即可
-
启动nacos
现在重新启动nacos
sh startup.sh ## 官网中推荐单机启动 sh startup.sh -m standalone
可以登录网页端进行配置服务管理。有一点,项目启动需要时间,api调不通可以稍微等一会儿
ip:port/nacos/#/login
帐号密码:
nacos/nacos
-
项目启动
此后以127.0.0.1代替ip,以8848代替port
nacos配置发布
-
根据提供的open-api发布配置
POST http://1.15.123.181:8848/nacos/v1/cs/configs?dataId=example&group=DEFAULT_GROUP&content=useLocalCache=true
-
根据open-api获取配置
GET http://1.15.123.181:8848/nacos/v1/cs/configs?dataId=example&group=DEFAULT_GROUP
结果
useLocalCache=true
-
springBoot项目配置获取配置
pom.xml新增依赖
<dependency> <groupId>com.alibaba.boot</groupId> <artifactId>nacos-config-spring-boot-starter</artifactId> <version>0.2.7</version> </dependency>
application.properties新增配置
nacos.config.server-addr=127.0.0.1:8848
java代码新增
@SpringBootApplication @ComponentScan(basePackages = {"com.paditang"}) ## 指定nacso配置数据仓库ID @NacosPropertySource(dataId = "example", autoRefreshed = true) public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); } }
@RestController @RequestMapping("test") public class TestController { @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true) private boolean useLocalCache; @NacosInjected private NamingService namingService; @GetMapping("default") public String orderRegionList() { return "test"; } @GetMapping("getConfig") public String getConfig() { return String.valueOf(useLocalCache); } }
启动项目后,调用
getConfig
接口,可以得到true的结果。
nacos服务发布
-
open-api 注册服务
POST http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=example&ip=127.0.0.1&port=8080
-
springboot项目配置变更
pom.xml新增
<dependency> <groupId>com.alibaba.boot</groupId> <artifactId>nacos-discovery-spring-boot-starter</artifactId> <version>0.2.7</version> </dependency>
application.properties新增配置
nacos.config.server-addr=127.0.0.1:8848
java代码
@RestController @RequestMapping("test") public class TestController { @NacosInjected private NamingService namingService; @GetMapping("getService") @ResponseBody public List<Instance> get(@RequestParam String serviceName) throws NacosException { return namingService.getAllInstances(serviceName); } }
结语
以上便是nacos入门的内容,主要有关基础配置和基础发布。后续如果有关nacos的深入使用,再以系列文的形式更新吧。