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

这篇具有很好参考价值的文章主要介绍了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工具类

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());文章来源地址https://www.toymoban.com/news/detail-499141.html

/**
 * 更新限流规则
 *
 * @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;
 }

到了这里,关于springboot获取nacos的服务列表、实例列表及修改实例、发布配置等的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包