当前位置: 首页 > 工具软件 > open-api > 使用案例 >

nacos解析-使用Open API管理配置

郑星辰
2023-12-01

本文基于nacos-2.0.3版本

nacos提供了功能丰富的Open API,使得我们可以使用http协议访问服务端,并管理服务端的配置数据。具体的功能可以参考下面网页:

https://nacos.io/zh-cn/docs/open-api.html

下面代码借助nacos的工具类,使用Open API提供了配置的增删改查功能。

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.common.constant.HttpHeaderConsts;
import com.alibaba.nacos.common.http.HttpClientConfig;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.client.request.JdkHttpClientRequest;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.alibaba.nacos.common.utils.VersionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NcoasClient {
    private static NacosRestTemplate template;
    public static void main(String[] args) throws Exception {
        //超时时间
        HttpClientConfig httpClientConfig= HttpClientConfig.builder().setConTimeOutMillis(5000).setReadTimeOutMillis(5000 >> 1).build();
        //JdkHttpClientRequest内部创建与服务端的连接
        JdkHttpClientRequest request=new JdkHttpClientRequest(httpClientConfig);
        //模板类,对URL地址和参数做处理,并调用JdkHttpClientRequest
        template=new NacosRestTemplate(LoggerFactory.getLogger("root"),request);

        Map<String, String> params = new HashMap<String, String>(2);
        params.put("dataId", "example");
        params.put("group", "DEFAULT_GROUP");

        Header newHeaders = getSpasHeaders("UTF-8");//配置HTTP报文头
        Query query = Query.newInstance().initParams(params);
        //删除配置
        deleteConfig(newHeaders,query);
        //发布配置
        publishConfig(newHeaders,query);
        //查询配置
        queryConfig(newHeaders,query);
        //查询配置历史版本
        queryConfigHistoryInfo(newHeaders,query);
    }
    public static void deleteConfig(Header headers,Query query)throws Exception{
        HttpRestResult<String> response=template.delete("http://127.0.0.1:8848/nacos"+ Constants.CONFIG_CONTROLLER_PATH,headers,query,String.class);
        if (response.ok()) {
            List<String> lines = IoUtils.readLines(new StringReader(response.getData()));
            lines.stream().forEach(System.out::println);
        }
    }

    public static void publishConfig(Header headers,Query query)throws Exception{
        query.addParam("content","test=1111");
        HttpRestResult<String> response=template.post("http://127.0.0.1:8848/nacos"+ Constants.CONFIG_CONTROLLER_PATH,headers,query,null,String.class);
        if (response.ok()) {
            List<String> lines = IoUtils.readLines(new StringReader(response.getData()));
            lines.stream().forEach(System.out::println);
        }
    }

    public static void queryConfig(Header headers,Query query)throws Exception{

        HttpRestResult<String> response=template.get("http://127.0.0.1:8848/nacos"+ Constants.CONFIG_CONTROLLER_PATH,headers,query,String.class);
        if (response.ok()) {
            List<String> lines = IoUtils.readLines(new StringReader(response.getData()));
            lines.stream().forEach(System.out::println);
        }
    }

    public static void queryConfigHistoryInfo(Header headers,Query query)throws Exception{
        query.addParam("nid","2");
        HttpRestResult<String> response=template.get("http://127.0.0.1:8848/nacos"+ Constants.BASE_PATH+"/history",headers,query,String.class);
        if (response.ok()) {
            List<String> lines = IoUtils.readLines(new StringReader(response.getData()));
            lines.stream().forEach(System.out::println);
        }
    }
    private static Header getSpasHeaders(String encode) throws Exception {
        Header header = Header.newInstance();
        String ts = String.valueOf(System.currentTimeMillis());
        String token = MD5Utils.md5Hex(ts + ParamUtil.getAppKey(), Constants.ENCODE);
        header.addParam(Constants.CLIENT_APPNAME_HEADER, ParamUtil.getAppName());
        header.addParam(Constants.CLIENT_REQUEST_TS_HEADER, ts);
        header.addParam(Constants.CLIENT_REQUEST_TOKEN_HEADER, token);
        header.addParam(HttpHeaderConsts.CLIENT_VERSION_HEADER, VersionUtils.version);
        header.addParam("exConfigInfo", "true");
        header.addParam(HttpHeaderConsts.REQUEST_ID, UuidUtils.generateUuid());
        header.addParam(HttpHeaderConsts.ACCEPT_CHARSET, encode);
        return header;
    }
}
 类似资料: