1 服务注册中心
上pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!--nacos注册中心依赖-->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.1</version>
</dependency>
<!--nacos配置中心 如果只是上注册中那这个就不用了加了-->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.1</version>
</dependency>
<dependencies>
这里需要注意:
版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本。
srping boot 和 nacos 注册中心的依赖的版本需要对上
application.yml 中的配置文件:
nacos:
discovery:
server-addr: 127.0.0.1:8848
config:
server-addr: 127.0.0.1:8848
到Nacos的稳定版本下载地址https://github.com/alibaba/nacos/releases,
我用的是nacos-server-1.3.1,
链接:https://pan.baidu.com/s/1hRe1vB6Do0bmXVHPT9gMFA
提取码:xl96
解压后到bin目录下启动startup.cmd
启动nacos
访问http://localhost:8848/nacos/index.html ,账号和密码都是nacos ,此时应用还不能在nacos 的注册中心中找到提供的服务。
利用postman这类工具 发送put请求,请求注册服务
http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=oa&ip=127.0.0.1&port=8090 请求成功后会返回一个ok
三个参数分别是服务名,服务的ip地址和对应端口。
这样就可以在nacos 上找到你的服务了
2 nacos作为配置中心
直接拿上面的配置文件中的配置和对应的pom。
启动类上添加
@NacosPropertySource(dataId = "example", autoRefreshed = true) 添加应用对应的数据id
配置文件
对应的接口
初始的配置
现在我们到nacos中去修改下对应的配置
这里的Data ID要和启动内上的 @NacosPropertySource(dataId = "example", autoRefreshed = true) 的dataId 一致
发布后 访问接口可以看到配置中心的文件生效了