先吐槽一下
今天就為了能在,Nacos服務(wù)里面注冊SpringBoot服務(wù)衅枫,折騰了一整天映胁。
主要是市面上的視頻還有很多文章都比較早以前有版本現(xiàn)在不能用绽左,官方的文檔對我這種小白來說很不友好,很多細節(jié)沒有寫到履怯,今天在這邊做個總結(jié)回还。
Nacos安裝運行
這就沒什么好說的,根據(jù)官方的文檔叹洲,這步驟也比較少柠硕,比較容易操作。
版本
我用的 SpringBoot 是2.5.2的版本 Nacos能用在這個版本的版本不多运提,我只測試了幾個版本
0.2.7 報錯
0.2.4 可以用
0.2.3 可以用
0.2.1 沒反映
下面是Nacos的一些版本
image.png
配置 注冊
這是官方文檔的截圖蝗柔,注意紅框的部分。 要真這樣配置的話你是不可能能注冊成功的民泵。當然癣丧,我說的是自動注冊(手動注冊的跳過)
image.png
還有一個關(guān)鍵的配置在那里呢?跟我的載圖來
image.png
image.png
image.png
關(guān)鍵的來了栈妆,默認是關(guān)閉的胁编,要自己開
image.png
經(jīng)過上面這些步驟,完了之后鳞尔,你就可以把項目跑起來了嬉橙,完美
image.png
發(fā)現(xiàn)
發(fā)現(xiàn)服務(wù)就比較簡單了
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);
}
}