spring boot 向nacos注册方式,以及遇见的报错(boot!boot! 不是cloud!)

一、首先添加nacos注册发现的pom依赖

        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-discovery-spring-boot-starter</artifactId>
            <version>0.2.3</version>
        </dependency>

二、application.properties文件中添加nacos的配置

nacos.discovery.server-addr=你的nacos地址:你的nacos端口

 三、在项目启动类中添加配置,启动时向nacos注册服务

    @NacosInjected
    private NamingService namingService;
    @Value("${spring.application.name}")
    private String applicationName;
    @PostConstruct
    public void registerInstance() throws NacosException {
        namingService.registerInstance(applicationName,"127.0.0.1",9193);
    }

以上就是spring boot 的注册方式,比较简单,项目启动后注册成功

 

 但是在第一次配置的时候发生了一些问题,项目启动报错:注册失败,然后追踪

namingService.registerInstance方法的源码,发现是调用httpclient注册的时候报错,源码中有一部分代码如下:
 public String callServer(String api, Map<String, String> params, String curServer, String method) throws NacosException {
        List<String> headers = Arrays.asList("Client-Version", "Nacos-Java-Client:v0.2.1", "Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive", "RequestId", UuidUtil.generateUuid());
        if (!curServer.contains(":")) {
            curServer = curServer + ":" + 8848;
        }

        String url = HttpClient.getPrefix() + curServer + api;
        HttpResult result = HttpClient.request(url, headers, params, "UTF-8", method);
        if (200 == result.code) {
            return result.content;
        } else if (304 == result.code) {
            return "";
        } else {
            LogUtils.LOG.error("CALL-SERVER", "failed to req API:" + HttpClient.getPrefix() + curServer + api + ". code:" + result.code + " msg: " + result.content);
            throw new NacosException(500, "failed to req API:" + HttpClient.getPrefix() + curServer + api + ". code:" + result.code + " msg: " + result.content);
        }
    }

发现,http接口的返回结果报错:cluster name can only have these characters: 0-9a-zA-Z-

查了很多资料发现是pom引入的版本问题,改为最新版本,注册成功

posted @ 2019-09-02 11:08  夜洛IT后端技术分享  阅读(3372)  评论(0编辑  收藏  举报