先吐槽一下
今天就为了能在,Nacos服务里面注册SpringBoot服务,折腾了一整天。
主要是市面上的视频还有很多文章都比较早以前有版本现在不能用,官方的文档对我这种小白来说很不友好,很多细节没有写到,今天在这边做个总结。
Nacos安装运行
这就没什么好说的,根据官方的文档,这步骤也比较少,比较容易操作。
版本
我用的 SpringBoot 是2.5.2的版本 Nacos能用在这个版本的版本不多,我只测试了几个版本
0.2.7 报错
0.2.4 可以用
0.2.3 可以用
0.2.1 没反映
下面是Nacos的一些版本

配置 注册
这是官方文档的截图,注意红框的部分。 要真这样配置的话你是不可能能注册成功的。当然,我说的是自动注册(手动注册的跳过)

还有一个关键的配置在那里呢?跟我的载图来



关键的来了,默认是关闭的,要自己开

经过上面这些步骤,完了之后,你就可以把项目跑起来了,完美

发现
发现服务就比较简单了
mport com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.google.gson.Gson;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@Component
@RestController
public class TestController {
@NacosInjected
private NamingService namingService ;
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public String test() throws NacosException {
Gson gjson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
// 拿到 接口信息
Instance instance = namingService.selectOneHealthyInstance("SPRING_BOOT_SERVICE");
map.put("ip", instance.getIp());
map.put("port",instance.getPort());
return gjson.toJson(map);
}
}
网友评论