行业知识
SpringCloud-Alibaba-Nacos教程
2026-11-14 10:37:17
来源:互联网转载
SpringCloud-Alibaba-Nacos教程
下载地址
https://github.com/alibaba/nacos/releases/tag/2.2.3
直接进入bin包 运行cmd命令
startup.cmd -m standalone
运行成功后
进入nacos可视化页面
账号密码默认都是nacos
http://localhost:8848/nacos
微服务入驻Nacos服务注册中心
1.Maven依赖
com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery org.springframework.cloud spring-cloud-starter-loadbalancer
2.application.yaml配置
# nacos配置spring: application: name: nacos-config-client #以此名入驻服务注册中心 cloud: nacos: discovery: server-addr: localhost:8848 #Nacos服务注册中心地址
3.启动类
@SpringBootApplication@EnableDiscoveryClientpublic class Main3377 { public static void main(String[] args) { SpringApplication.run(Main3377.class,args); }} 此时启动就会入驻到nacos服务注册中心
Nacos分布式服务配置中心
1.maven依赖
org.springframework.cloud spring-cloud-starter-bootstrap com.alibaba.cloud spring-cloud-starter-alibaba-nacos-config com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery
2.bootstrap.yaml
为什么要加bootstrap.yaml 因为它的优先级是系统级的,并且微服务想要注册服务,肯定要先让服务注册中心配置好
# nacos配置spring: application: name: nacos-config-client #以此名入驻服务注册中心 cloud: nacos: discovery: server-addr: localhost:8848 #Nacos服务注册中心地址 config: server-addr: localhost:8848 #Nacos作为配置中心地址 file-extension: yaml #指定yaml格式的配置 #group: PROD_GROUP #如果设置了groupid #namespace: Prod_Namespace #如果设置了namespace# nacos端配置文件DataId的命名规则是:# nacos-config-client dev yaml ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}# 本案例的DataID是:nacos-config-client-dev.yaml 3.application.yaml
server: port: 3377spring: profiles: active: dev # 表示开发环境 #active: prod # 表示生产环境 #active: test # 表示测试环境
4.启动类还是那一套
5.controller类
需要添加@RefreshScope 这样 你在服务配置中心那改了就会实时获取到修改过的配置
@RestController@RefreshScope //在控制器类加入@RefreshScope注解使当前类下的配置支持Nacos的动态刷新功能。public class NacosConfigClientController{ @Value("${config.info}") private String configInfo; @GetMapping("/config/info") public String getConfigInfo() { return configInfo; }} 6.nocas新建配置
7.测试结果
GET http://localhost:3377/config/info
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 33
Date: Sat, 09 Mar 2024 11:26:09 GMT
Keep-Alive: timeout=60
Connection: keep-alive
nihao nihao hello hello version 1
Response code: 200; Time: 110ms (110 ms); Content length: 33 bytes (33 B)
上一篇:怎么打开登云服务器权限?
下一篇:账号登陆服务器怎么设置?