下载地址
https://github.com/alibaba/nacos/releases/tag/2.2.3
直接进入bin包 运行cmd命令
startup.cmd -m standalone
运行成功后
进入nacos可视化页面
账号密码默认都是nacos
http://localhost:8848/nacos
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-loadbalancerartifactId>
dependency>
# nacos配置
spring:
application:
name: nacos-config-client #以此名入驻服务注册中心
cloud:
nacos:
discovery:
server-addr: localhost:8848 #Nacos服务注册中心地址
@SpringBootApplication
@EnableDiscoveryClient
public class Main3377 {
public static void main(String[] args) {
SpringApplication.run(Main3377.class,args);
}
}
此时启动就会入驻到nacos服务注册中心
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-bootstrapartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
为什么要加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
server:
port: 3377
spring:
profiles:
active: dev # 表示开发环境
#active: prod # 表示生产环境
#active: test # 表示测试环境
需要添加@RefreshScope 这样 你在服务配置中心那改了就会实时获取到修改过的配置
@RestController
@RefreshScope //在控制器类加入@RefreshScope注解使当前类下的配置支持Nacos的动态刷新功能。
public class NacosConfigClientController
{
@Value("${config.info}")
private String configInfo;
@GetMapping("/config/info")
public String getConfigInfo() {
return configInfo;
}
}
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)