本文已参与「新人创作礼」活动,一起开启掘金创作之路。
windows环境下部署nacos
下载
nacos官网下载开源版:https://nacos.io/zh-cn/index.html
解压后是这个样子:
启动:
错误:直接进入bin目录下点击startup.cmd,会报错,而是需要本地单机模式启动;到bin目录下 打开cmd窗口,执行命令 startup.cmd -m standalone ;或者更改.cmd中的配置文件 set MODE="standalone" 启动成功:
访问:http://localhost:8848/nacos/index.html#/login
SpringBoot集成
pom文件
新增依赖
dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>
application.yaml文件
测试代码
//测试 获取nacos配置文件
@Controller
@RequestMapping("config")
public class ConfigController {
@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
private boolean useLocalCache;
@RequestMapping(value = "/get", method = GET)
@ResponseBody
public boolean get() {
return useLocalCache;
}
}
//测试服务发现
@Controller
@RequestMapping("discovery")
public class DiscoveryController {
@NacosInjected
private NamingService namingService;
@RequestMapping(value = "/get", method = GET)
@ResponseBody
public List<Instance> get(@RequestParam String serviceName) throws NacosException {
return namingService.getAllInstances(serviceName);
}
}
测试验证
获取配置文件
1、启动服务
2、访问 http://localhost:8080/config/get 返回 false
3、postMan访问 http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=example&group=DEFAULT_GROUP&content=useLocalCache=true
4、按照道理说 再次调用 http://localhost:8080/config/get 会返回 true,可还是给返回 false,连续搞了好久,后来问公司架构师,搜嘎....坑
注册服务
1、启动服务 2、访问 http://localhost:8080/discovery/get?serviceName=exampl 返回 [] 3、postMan访问 http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=example&ip=127.0.0.1&port=8080
4、 再次调用 http://localhost:8080/discovery/get?serviceName=exampl 返回如下图: