springboot获取nacos的服务列表、实例列表及修改实例、发布配置等

2023-11-15

1.通过java-sdk的方式发布配置

官方文档说明:https://nacos.io/zh-cn/docs/sdk.html
https://nacos.io/zh-cn/docs/open-api.html

1.1构造ConfigService工具类

package com.redxun.config;

import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 *  构造ConfigService工具类。
 */
@Configuration
public class NacosConfigConfigration implements EnvironmentAware {

    private Environment env;

    private static final String NACOS_ADDRESS="nacos.address";
    private static final String NACOS_NAMESPACE="nacos.namespace";
    private static final String NACOS_USERNAME="nacos.username";
    private static final String NACOS_PASSWORD="nacos.password";

    @Override
    public void setEnvironment(Environment environment) {
        this.env=environment;
    }

    @Bean
    public ConfigService configService() throws NacosException {
        NacosConfigService configService=new NacosConfigService();
        String address=this.env.getProperty(NACOS_ADDRESS);
        String namespace=this.env.getProperty(NACOS_NAMESPACE);
        String username=this.env.getProperty(NACOS_USERNAME);
        String password=this.env.getProperty(NACOS_PASSWORD);

        ConfigService service= configService.getConfigService(address,namespace,username,password);
        return  service;
    }
}

1.2构造NacosConfig配置

package com.redxun.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.util.StringUtils;

import java.util.Properties;

/**
 * 构造NacosConfig配置。
 */
public class NacosConfigService {



    public ConfigService getConfigService(String address,String namespace,String username,String password) throws NacosException {

        if(StringUtils.isEmpty(address)){
            address="localhost:8848";
        }
        if(StringUtils.isEmpty(namespace)){
            namespace="local";
        }
        if(StringUtils.isEmpty(username)){
            username="nacos";
        }
        if(StringUtils.isEmpty(password)){
            password="nacos";
        }
        Properties properties = new Properties();
        // nacos服务器地址
        properties.put(PropertyKeyConst.SERVER_ADDR, address);
        // 配置中心的命名空间id
        properties.put(PropertyKeyConst.NAMESPACE, namespace);
        properties.put(PropertyKeyConst.USERNAME, username);
        properties.put(PropertyKeyConst.PASSWORD, password);

        ConfigService configService = NacosFactory.createConfigService(properties);
        return configService;
    }


}

1.3获取配置、修改后、发布配置

获取配置:String config = configService.getConfig(dataId, groupId, 0L);

发布配置:configService.publishConfig(dataId, groupId, conf.toJSONString());

/**
 * 更新限流规则
 *
 * @param entity
 * @return
 */
@Transactional(rollbackFor = Exception.class)
public int update(SysInterfaceApiFlow entity) {
    try {
        NamingService nacosNamingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());

        List<Instance> instances = nacosNamingService.getAllInstances("serviceName");
        //查询nacos上面的限流配置
        String config = configService.getConfig(dataId, groupId, 0L);
        if (StringUtils.isEmpty(config)) {
            config = "[]";
        }
        JSONArray conf = JSONArray.parseArray(config);
        //把当前的实体类转化为nacos限流配置
        if (null != entity) {
            JSONObject json = buildFlowJson(entity);
            Iterator iterator = conf.iterator();
            while (iterator.hasNext()) {
                Map map = (Map) iterator.next();
                if (map.get("id").equals(json.get("id"))) {
                    iterator.remove();//删除id相同的配置项
                }
            }
            //删除之后再新增当前配置项
            conf.add(json);
        }
        //发布全部的限流配置
        int result = sysInterfaceApiFlowMapper.updateById(entity);
        if (result > 0) {
            configService.publishConfig(dataId, groupId, conf.toJSONString());
        }
        return result;
    } catch (NacosException e) {
        log.error("添加限流规则出错" + e.getMessage());
        throw new BusinessException("添加限流规则出错" + e.getMessage());
    }
}

2.获取nacos上面的微服务列表、详情(包括集群详情)

2.1通过api的方式获取列表(sdk和open-api方式没有分页和条件查询参数)

2.1.1先获取token

/**
  * nacos获取accessToken
  *
  * @return
  * @throws Exception
  */
 private String getAccessToken() throws Exception {
     Map map = new HashMap<>();
     map.put("username", username);
     map.put("password", password);
     String result = HttpClientUtil.postFromUrl("http://" + address + "/nacos/v1/auth/login", map);
     JSONObject jsonObject = JSONObject.parseObject(result);
     String accessToken = jsonObject.getString("accessToken");
     return accessToken;
 }

2.1.2分页获取服务列表

/**
  * nacos获取service
  *
  * @return
  */
 private String getNacosService(String accessToken, String serviceName, String groupName, long current, long size) throws Exception {
     Map mapService = new HashMap<>();
     mapService.put("accessToken", accessToken);
     mapService.put("hasIpCount", "true");
     mapService.put("withInstances", "false");
     mapService.put("serviceNameParam", serviceName);
     mapService.put("clusterName", "DEFAULT");
     mapService.put("groupNameParam", groupName);
     mapService.put("pageSize", String.valueOf(size));
     mapService.put("pageNo", String.valueOf(current));
     mapService.put("namespaceId", namespace);
     String serviceResult = HttpClientUtil.getFromUrl("http://" + address + "/nacos/v1/ns/catalog/services", mapService);
     return serviceResult;
 }

2.1.3分页获取实例列表

/**
  * nacos获取instances
  *
  * @param accessToken
  * @param serviceName
  * @param current
  * @param size
  * @return
  * @throws Exception
  */
 private String getInsResult(String accessToken, String serviceName, long current, long size) throws Exception {
     Map mapIns = new HashMap<>();
     mapIns.put("accessToken", accessToken);
     mapIns.put("serviceName", serviceName);
     mapIns.put("clusterName", "DEFAULT");
     mapIns.put("groupName", "DEFAULT_GROUP");
     mapIns.put("pageSize", String.valueOf(size));
     mapIns.put("pageNo", String.valueOf(current));
     mapIns.put("namespaceId", namespace);
     String insResult = HttpClientUtil.getFromUrl("http://" + address + "/nacos/v1/ns/catalog/instances", mapIns);
     return insResult;
 }

2.2通过java-sdk获取(没有分页参数、弃用)

NamingService nacosNamingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
NamingMaintainService namingMaintainService = nacosServiceManager.getNamingMaintainService(nacosDiscoveryProperties.getNacosProperties());
List<ServiceInfo> serviceInfos = nacosNamingService.getSubscribeServices();
List<Instance> instances = nacosNamingService.getAllInstances("serviceName");

3.修改实例权重、上下线等(java-sdk方式)

/**
  * 对服务进行加权降权处理
  *
  * @return
  * @throws Exception
  */
 @MethodDefine(title = "对服务进行加权降权处理", path = "/updateInstance", method = HttpMethodConstants.POST)
 @ApiOperation(value = "对服务进行加权降权处理", notes = "对服务进行加权降权处理")
 @PostMapping(value = "/updateInstance")
 public JsonResult updateInstance(@RequestBody Instance instance, String type, String serviceName) throws Exception {
     JsonResult jsonResult = JsonResult.getSuccessResult("操作成功!");
     try {
         NamingMaintainService namingMaintainService = nacosServiceManager.getNamingMaintainService(nacosDiscoveryProperties.getNacosProperties());
         double weight = instance.getWeight();
         if (StringUtils.isNotEmpty(type) && type.equals("0")) {//加权
             weight++;
         } else if (StringUtils.isNotEmpty(type) && type.equals("1")) {//降权
             weight--;
         } else if (StringUtils.isNotEmpty(type) && type.equals("2")) {//下线
             instance.setEnabled(false);
         } else if (StringUtils.isNotEmpty(type) && type.equals("3")) {//上线
             instance.setEnabled(true);
         }
         instance.setWeight(weight);
         namingMaintainService.updateInstance(serviceName, instance);

     } catch (Exception ex) {
         jsonResult.setSuccess(false);
     }
     return jsonResult;
 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot获取nacos的服务列表、实例列表及修改实例、发布配置等 的相关文章

随机推荐

  • 2022-04-20 Sass学习笔记(四) Sass的混入(mixin),继承(extend)和导入(import)

    1 Sass混入 mixin 与 include mixin 指令允许我们定义一个可以在整个样式表中重复使用的样式 include 指令可以将混入 mixin 引入到文档中 语法 定义 mixin mixin name 使用 selecto
  • 【华为OD机试真题 JAVA】连续出牌数量

    JS版 华为OD机试真题 JS 连续出牌数量 标题 连续出牌数量 时间限制 1秒 内存限制 262144K 语言限制 不限 有这么一款单人卡牌游戏 牌面由颜色和数字组成 颜色为红 黄 蓝 绿中的一种 数字为0 9中的一个 游戏开始时玩家从手
  • 【H5】 canvas图像各种合成详解

    本素材来源 https www cnblogs com hzj680539 p 5068487 html 尊重第一作者 把知识奉献给大家 简易直观图 黄色圆为原图 蓝色正方形为新图 红色圆为新图 蓝色为原图 globalCompositeO
  • 《SQLi-Labs》03. Less 11~15

    sqli 索引 Less 11 题解 原理 Less 12 题解 Less 13 题解 Less 14 题解 Less 15 题解 原理 sqli 开启新坑 索引 Less 11 POST 回显注入 字符型 Less 12 POST 回显注
  • 面试总结(六):搜索索引

    问题导读 1 如何理解用户输入查询语句 2 如何根据得到的文档和查询语句的相关性 对结果进行排序 3 如何计算权重 Term weight 过程 4 如何判断Term之间的关系从而得到文档相关性 搜索索引到这里似乎我们可以宣布 我们找到想要
  • 为什需要采用增广拉格朗日函数

    为什需要采用增广拉格朗日函数 目标函数的可以转化为Lagrangian函数的最小 称之为对偶函数 dual function d
  • moveit是如何控制机械臂运动的

    确定机械臂的状态 MoveIt会读取机械臂的当前状态 包括关节角度 位置和速度等信息 获取规划请求 MoveIt会接收到一个规划请求 其中包含了机械臂需要执行的任务和目标 进行运动规划 MoveIt会对机械臂的当前状态和任务目标进行运动规划
  • Jsvc

    Jsvc How to detach the Java daemon from the shell script Toolbox for IT Groups How to detach the Java daemon from the sh
  • 学习多线程,创建多线程的三种方式

    多线程 并发与并行 并发 两个或多个事件在同一个时间段内发生 交替执行 并行 两个或多个事件在同一个时刻发生 同时执行 进程与线程 进程 进入到内存中的程序 线程 进程中的一个执行单元 负责当前进程中程序的执行 一个进程中至少有一个线程 一
  • 教你如何在VSCode中使用markdown标记语言并转为word

    目录 准备工作 正文开始 准备工作 插件 1 安装 pandoc https pandoc org installing html Windows用户进入官网后 直接点最大的那个按钮就行了 其他操作系统找到相应的下载点 这里我就不多讲了 实
  • 【解决】IDEA默认的代码格式化快捷键是失效

    Ctrl Alt L 网易云的快捷键 关掉网易云后 IDEA格式化快捷键就可以使用了
  • markdown表格合并单元格,嵌入HTML语法

    markdown的语法并不支持表格单元格合并 但可以通过嵌入HTML来解决 例如想实现这样的单元格合并效果 网络状态指示引脚的工作状态 引脚名 引脚工作状态 所指示的网络状态 NET STATUS 慢闪 200 ms 高 1800 ms 低
  • Java Scheduled定时任务

    开启定时任务步骤流程 1 在启动类添加注解 注意 千万不要忘记 EnableScheduling 2 在具体的方法上添加定时任务注解 Scheduled cron 0 0 3 每3个小时触发一次 3 定时任务开启时间 常用的 Schedul
  • SpringBoot集成Redis来实现缓存技术方案

    为什么80 的码农都做不了架构师 gt gt gt 概述 在我们的日常项目开发过程中缓存是无处不在的 因为它可以极大的提高系统的访问速度 关于缓存的框架也种类繁多 今天主要介绍的是使用现在非常流行的NoSQL数据库 Redis 来实现我们的
  • 【VS2010学习笔记】【异常处理】general error c1010070: Failed to load and parse the manifest.

    在VS2010编程中 有时编译会遇到这样的错误 general error c1010070 Failed to load and parse the manifest 解决方法就是在解决方案中将后缀名为manifest的文件删除 再编译即
  • css 第二行的元素设置margin-top间隔

    css 第二行的元素设置margin top间隔
  • Extjs的Form表单提交方式

    Extjs的Form表单提交方式 一 直接提交 url写在表单中 var addForm new Ext FormPanel frame true url insertProject eva doType insertProject lab
  • PCIe5.0的Add-in-Card(AIC)金手指layout建议(三)

    PCIe5 0的Add in Card AIC 金手指layout建议 一 PCIe5 0的Add in Card AIC 金手指layout建议 二 前面两篇文章介绍了第一种金手指的layout建议 适用速率在32 0 GT s 以下介绍
  • 关于爬虫技术

    1 什么是爬虫 爬虫是一种自动化程序 它能够模拟人类用户访问网站的行为 从网站上抓取数据并保存到本地或者进行进一步处理 爬虫是一种非常常用的网络数据采集工具 可以用于搜索引擎 电商数据采集 舆情监测等多个领域 通过使用爬虫 可以自动化地获取
  • springboot获取nacos的服务列表、实例列表及修改实例、发布配置等

    1 通过java sdk的方式发布配置 官方文档说明 https nacos io zh cn docs sdk html https nacos io zh cn docs open api html 1 1构造ConfigService