新闻详情

新闻详情

首页 / 资讯中心 / 详情

【SpringCloud】应用获取nacos的服务列表、实例列表及修改实例、发布配置等

发布时间:2026/9/30 6:33:50来源:尧图网络
【SpringCloud】应用获取nacos的服务列表、实例列表及修改实例、发布配置等
1.通过java-sdk的方式发布配置官方文档说明https://nacos.io/zh-cn/docs/sdk.htmlhttps://nacos.io/zh-cn/docs/open-api.html1.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_ADDRESSnacos.address; private static final String NACOS_NAMESPACEnacos.namespace; private static final String NACOS_USERNAMEnacos.username; private static final String NACOS_PASSWORDnacos.password; Override public void setEnvironment(Environment environment) { this.envenvironment; } Bean public ConfigService configService() throws NacosException { NacosConfigService configServicenew NacosConfigService(); String addressthis.env.getProperty(NACOS_ADDRESS); String namespacethis.env.getProperty(NACOS_NAMESPACE); String usernamethis.env.getProperty(NACOS_USERNAME); String passwordthis.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)){ addresslocalhost:8848; } if(StringUtils.isEmpty(namespace)){ namespacelocal; } if(StringUtils.isEmpty(username)){ usernamenacos; } if(StringUtils.isEmpty(password)){ passwordnacos; } 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()); ListInstance 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 mapnew HashMap();map.put(username, username);map.put(password, password);String resultHttpClientUtil.postFromUrl(http:// address /nacos/v1/auth/login, map);JSONObject jsonObjectJSONObject.parseObject(result);String accessTokenjsonObject.getString(accessToken);returnaccessToken;}2.1.2分页获取服务列表/** * nacos获取service * * return */ private String getNacosService(String accessToken, String serviceName, String groupName, long current, long size)throws Exception{Map mapServicenew 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 serviceResultHttpClientUtil.getFromUrl(http:// address /nacos/v1/ns/catalog/services, mapService);returnserviceResult;}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 mapInsnew 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 insResultHttpClientUtil.getFromUrl(http:// address /nacos/v1/ns/catalog/instances, mapIns);returninsResult;}2.2通过java-sdk获取没有分页参数、弃用NamingService nacosNamingServicenacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());NamingMaintainService namingMaintainServicenacosServiceManager.getNamingMaintainService(nacosDiscoveryProperties.getNacosProperties());ListServiceInfoserviceInfosnacosNamingService.getSubscribeServices();ListInstanceinstancesnacosNamingService.getAllInstances(serviceName);3.修改实例权重、上下线等java-sdk方式/** * 对服务进行加权降权处理 * * return * throws Exception */ MethodDefine(title对服务进行加权降权处理, path/updateInstance, methodHttpMethodConstants.POST)ApiOperation(value对服务进行加权降权处理, notes对服务进行加权降权处理)PostMapping(value/updateInstance)public JsonResult updateInstance(RequestBody Instance instance, String type, String serviceName)throws Exception{JsonResult jsonResultJsonResult.getSuccessResult(操作成功!);try{NamingMaintainService namingMaintainServicenacosServiceManager.getNamingMaintainService(nacosDiscoveryProperties.getNacosProperties());double weightinstance.getWeight();if(StringUtils.isNotEmpty(type)type.equals(0)){//加权 weight;}elseif(StringUtils.isNotEmpty(type)type.equals(1)){//降权 weight--;}elseif(StringUtils.isNotEmpty(type)type.equals(2)){//下线 instance.setEnabled(false);}elseif(StringUtils.isNotEmpty(type)type.equals(3)){//上线 instance.setEnabled(true);}instance.setWeight(weight);namingMaintainService.updateInstance(serviceName, instance);}catch(Exception ex){jsonResult.setSuccess(false);}returnjsonResult;}
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

QC-LDPC编码原理与5G物理层实现详解 2026/9/30 12:05:46

QC-LDPC编码原理与5G物理层实现详解

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

阅读更多 →
PRD算法:从前端页面逆向到需求文档的高可用框架 2026/9/30 12:05:46

PRD算法:从前端页面逆向到需求文档的高可用框架

先说一个判断:PRD算法这个提法,容易让人觉得是某种排序或求解模型,但在产品和技术圈的语境里,PRD更多指的是产品需求文档。这篇文章想聊的也不是某个数学公式,而是如何用算法思维,把PRD这门看似"靠感觉…

阅读更多 →
TensorFlow生产级实践:SavedModel、tf.function与分布式训练 2026/9/30 12:05:46

TensorFlow生产级实践:SavedModel、tf.function与分布式训练

1. 这不是“装个库”那么简单:TensorFlow到底在解决什么问题? 很多人第一次听说TensorFlow,是在“Python深度学习环境配置”的教程里,或者在招聘JD上看到“熟悉TensorFlow者优先”。但如果你真去翻官方文档首页,第一句…

阅读更多 →
达梦数据库SQL实战:从语法兼容到迁移排错,一份能直接用的速查清单 2026/9/30 12:05:46

达梦数据库SQL实战:从语法兼容到迁移排错,一份能直接用的速查清单

1. 这份达梦SQL清单能帮你解决哪些问题达梦数据库(DM)在国内信创和央国企项目里出现的频率越来越高,很多原本写惯了Oracle、MySQL的人第一次接触时,最大的感受不是功能不够,而是“看着面熟,写起来处处要小心…

阅读更多 →
自定义Trait实战:统一业务契约的组合之道 2026/9/30 12:05:46

自定义Trait实战:统一业务契约的组合之道

去年年底帮团队梳理一套订单系统的公共逻辑时,我发现最头疼的其实不是业务复杂度,而是同一类能力散落在各种类型上,方法名不一样、参数不一样、返回类型也不一样。后来我们用“自定义Traits”把校验、日志、排序、序列化这些横切能力统一成了…

阅读更多 →
四大云厂商算力选型指南:从显存估算到集群落地与成本优化 2026/9/30 12:05:39

四大云厂商算力选型指南:从显存估算到集群落地与成本优化

简介:这份PDF资料聚焦阿里云、华为云、腾讯云与百度智能云四大厂商的算力布局,面向关注云计算产业、数据中心建设与“东数西算”政策的从业者、研究者及投资分析人士,帮助读者系统理解算力竞赛的底层逻辑与竞争格局。资源为单个PDF文件&#…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉