Nacos 工具类

maven 引用http工具类

		<!--hutool 的http工具类-->
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-http</artifactId>
		</dependency>

Java 通过 http请求,操作nacos




import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.SneakyThrows;
import org.gitlab4j.api.GitLabApiException;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Nacos 工具类
 */
public class test3 {

    private static final  String serverAddr = "11.11.111.111:8848";
    private static final  String namespaceName = "project_dev_name"; //命名空间名 默认项目编码_环境,比如:
    private static final  String namespaceDesc = "描述";
    private static final  String customNamespaceId = "project_dev_id"; //命名空间ID 默认namespaceName
    private static final  String service_name = "service01"; //服务名称

    //项目
    private static final String project_name="zcnewproject06";

    @SneakyThrows
    public static void main(String[] args) {
//        createNacosNamespace();
        createOrUpdateProfile(null,null,"application.yml");
        getProfile();
    }

    /**
     * 查询配置文件
     * @param
     * @return
     * @throws GitLabApiException
     */
    public static void getProfile()   {
        String requestBodyStr = "show=all&group=DEFAULT_GROUP&dataId=" + project_name+"-"+ service_name + ".yml&tenant="+customNamespaceId+"&namespaceId="+customNamespaceId;
        String url =serverAddr+"/nacos/v1/cs/configs?"+requestBodyStr;
        HttpRequest request = HttpRequest.get(url)
                .header("Content-Type", "application/x-www-form-urlencoded")
                ;
        HttpResponse response = request.execute();
        //response 返回有值 配置已存在, 试试别的dataid和group的组合吧
        if (response.getStatus() == 200) {
            System.out.println("创建命名空间成功,返回结构为:" +response.body());
        } else {
            System.out.println("创建命名空间失败,状态码:" + response.getStatus());
            System.out.println("错误信息:" + response.body());
        }
    }


    /**
     * 创建或者更新配置文件
     * @param
     * @return
     * @throws GitLabApiException
     */
    public static void createOrUpdateProfile(String id, String md5,String fileName)   {
        FileReader fileReader = new FileReader(fileName);
        String content = fileReader.readString();
        System.out.println("文件内容:" + content);

        // 创建一个Map存储请求参数
        Map<String, String> params = new HashMap<>();
        params.put("type","yaml");
        params.put("group","DEFAULT_GROUP");
        params.put("dataId",project_name+"-"+ service_name );
        params.put("tenant",customNamespaceId);
        params.put("namespaceId",customNamespaceId);
        params.put("content",content);
        if (StrUtil.isBlank(id)) {
            params.put("id",id);
        }
        if (StrUtil.isBlank(md5)) {
            params.put("md5",md5);
        }

        // 将Map转换为URL编码格式的字符串
        String requestBodyStr = params.entrySet().stream()
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name());
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    return null;
                })
                .collect(Collectors.joining("&"));


        if(requestBodyStr == null){
            System.out.println("创建配置文件失败,请求参数解析有误");
        }
        String url =serverAddr+"/nacos/v1/cs/configs?";
        HttpRequest request = HttpRequest.post(url)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body(requestBodyStr)
                ;

        HttpResponse response = request.execute();

        if (response.getStatus() == 200) {
            System.out.println("创建命名空间成功,返回结构为:" +response.body());

        } else {
            System.out.println("创建命名空间失败,状态码:" + response.getStatus());
            System.out.println("错误信息:" + response.body());
        }
    }

    /**
     * 创建命名空间
     * @param
     * @return
     * @throws GitLabApiException
     */
    public static void createNacosNamespace()   {
        String requestBodyStr = "namespaceName=" + namespaceName + "&namespaceDesc="+namespaceDesc+"&customNamespaceId="+customNamespaceId;
        String url =serverAddr+"/nacos/v1/console/namespaces?"+requestBodyStr;
        HttpRequest request = HttpRequest.post(url)
                .header("Content-Type", "application/x-www-form-urlencoded")
                ;

        HttpResponse response = request.execute();

        if (response.getStatus() == 200) {
            System.out.println("创建命名空间成功,返回结构为:" +response.body());

        } else {
            System.out.println("创建命名空间失败,状态码:" + response.getStatus());
            System.out.println("错误信息:" + response.body());
        }
    }





}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
nacos-server-1.2.0.zip 包是从github上下载的官方源包 Nacos 1.2 踩坑记录 坑1: nacos-mysql.sql 文件中的 permissions 表, 创建的联合唯一键超长, sql文件里是512长度, 导致报 Specified key was too long; max key length is 767 bytes 解决方案1: 直接缩短到255长度 解决方案2: 修改数据库配置, set innodb_large_prefix=on 吐槽一下, 1.2.0版本比1.1.4版本多创建一个数据表, 为甚么前面的sql有引擎,有编码,有注释, 1.2.0新增的表没有这些? 发布之前不做sql的兼容? 强迫症患者表示很难受 坑2: windows版集群部署, 官方文档只交代了简单的配置, 集群模式启动命令中需要加上 -m, 这是在修改startup.cmd看到脚本发现的, 不加-m永远是单机模式... 单机模式: -m standalone 或不配置 -m 集群模式: -m 参数值不等于standalone皆可 压缩包提供了已经修改好的启动文件 startup.cmd, 并支持启动时可附带ip和端口的设置, 支持跨网段集群 下载学习的同学可以对照一下改动位置 linux环境对应修改startup.sh文件, 这个包本身是windows版, 所以我没做sh文件的改动 补充: 集群配置 1、修改 application.properties 末尾追加数据库配置, 用于集群环境下存储 Nacos 配置文件 spring.datasource.platform=mysql db.num=1 db.url.0=jdbc:mysql://ip:port/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true db.user=xxxx db.password=xxxxx 2、复制 cluster.conf.example 并重命名为 cluster.conf, 写入配置, 最少3个节点构成集群 192.168.1.2:8848 192.168.1.2:8849 192.168.1.2:8850 3、nginx反向代理配置, 因为我这里是单台机器 upstream nacos-server { server 127.0.0.1:8848; server 127.0.0.1:8849; server 127.0.0.1:8850; } server { listen 80; server_name localhost; location / { proxy_pass http://nacos-server; } } 4、启动集群, 写个脚本批量启动 startup_all.bat, 脚本代码如下 start startup.cmd -m -i 192.168.1.2 -p 8848 start startup.cmd -m -i 192.168.1.2 -p 8849 start startup.cmd -m -i 192.168.1.2 -p 8850 需要注意启动命令的 -i 和 -p 是我们自己加入的, 配置的ip和端口需要跟 cluster.conf 对应, 缺省127.0.0.1:8848 此时打开Nacos后台,能看到3个节点已构成集群模式: 节点Ip 节点状态 集群任期 Leader止时(ms) 心跳止时(ms) 192.168.1.2:8849 LEADER 1 16736 2500 192.168.1.2:8848 FOLLOWER 1 12510 2500 192.168.1.2:8850 FOLLOWER 1 16397 2500

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值