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());

/**
 * 更新限流规则
 *
 * @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;
 }
  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
### 回答1: 用 sklearn 库中的 KMeans 算法进行聚类分析后,可以使用 Matplotlib 库进行可视化。可以使用 scatter 方法绘制数据点,并使用不同颜色表示不同类别。代码示例如下: ``` from sklearn.cluster import KMeans from matplotlib import pyplot as plt # 进行 KMeans 聚类 kmeans = KMeans(n_clusters=3) kmeans.fit(X) # 绘制聚类结果 plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_) plt.show() ``` 其中 X 是待聚类数据,n_clusters 是聚类数量。 ### 回答2: k-means是一种常见的聚类算法,在机器学习中应用广泛。sklearn库中提供了k-means算法的实现,同时也支持对聚类结果进行可视化展示,方便用户观察聚类结果并进一步分析。 在sklearn中,通过导入sklearn.cluster中的KMeans类来使用k-means算法。在使用KMeans类前,需要指定算法参数,如簇类数量、初始质心位置等。具体参数配置可参照官方文档进行设置。 针对聚类结果的可视化展示,sklearn提供了多种方法。以下介绍两种常见的可视化方法: 1. 绘制散点图 将聚类结果用散点图进行可视化是一种常见方法。在绘制散点图时,通常根据聚类簇别,对不同数据点进行颜色编码,以便用户能够更清晰地区分不同类别的数据点。代码示例: ``` import matplotlib.pyplot as plt # 聚类簇别结果保存在labels中 # 聚类中心位置保存在cluster_centers_中 # X为原始数据 for i in range(n_clusters): plt.scatter(X[labels == i, 0], X[labels == i, 1], s=30, label='Cluster %d' % (i+1)) plt.scatter(cluster_centers_[:, 0], cluster_centers_[:, 1], marker='*', s=200, label='Centroids') plt.legend() plt.show() ``` 2. 绘制决策边界 决策边界用于划分不同聚类簇别的区域,相邻区域的簇别不同。通过绘制决策边界,可以更清晰地展示不同聚类簇别的分布情况。代码示例: ``` from sklearn.metrics import pairwise_distances_argmin # 聚类簇别结果保存在labels中 # X为原始数据 def plot_kmeans(kmeans, X, n_clusters=3, rseed=0, ax=None): labels = kmeans.fit_predict(X) # 绘制决策边界 ax = ax or plt.gca() ax.axis('equal') ax.scatter(X[:, 0], X[:, 1], c=labels, s=40, cmap='viridis', zorder=2) # 绘制聚类中心 centers = kmeans.cluster_centers_ radii = [cdist(X[labels == i], [center]).max() for i, center in enumerate(centers)] for c, r in zip(centers, radii): ax.add_patch(plt.Circle(c, r, fc='#CCCCCC', lw=3, alpha=0.5, zorder=1)) kmeans = KMeans(n_clusters=3, random_state=0) plot_kmeans(kmeans, X) plt.show() ``` 无论是绘制散点图还是绘制决策边界,k-means聚类的可视化展示都能够为用户提供全局性的聚类结果,方便用户进一步分析和探索数据。 ### 回答3: 机器学习中的K均值聚类算法是一种无监督学习方法,可用于将数据点分成不同的类别。在scikit-learn(sklearn)包中,我们可以使用KMeans类来实现K均值聚类算法,同时通过可视化的方式更直观地了解到该算法的结果。 首先,我们需要生成一些数据。在这里,可以通过使用make_blobs函数生成随机的数据点,并将其分成不同的类别。然后,我们可以使用KMeans类对这些数据点进行聚类分析。在KMeans类中,我们可以设置聚类的数量(也称为k值)和迭代次数(max_iter)。例如,我们可以设置k值为3,迭代次数为100,并使用fit_predict函数进行聚类,将每个数据点分配到其所属的簇中。 接下来,我们可以使用matplotlib库来可视化聚类结果。对于二维数据,我们可以使用散点图来显示每个数据点所属的簇。我们还可以使用不同的颜色来区分不同的簇,使得结果更加直观。在二维数据的情况下,可以使用plt.scatter函数来绘制散点图,使用不同的颜色为不同的簇分配不同的值。我们还可以使用KMeans类的cluster_centers_属性来显示每个簇的中心点,用不同的标记区分每个簇的中心点。 总之,通过使用sklearn kmeans聚类可视化,我们可以更好地了解K均值聚类算法的工作原理,并更好地理解每个数据点所属的不同簇。此外,该过程也可以帮助我们选择最佳的k值和max_iter值,以便获得更好的聚类结果。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值