You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.0 KiB

package Util;
import com.jfinal.kit.PathKit;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class K8sClientTest {
//Master /root/.kube/config文件拷贝过来
public static String kubeConfigPath = PathKit.getRootClassPath() + "\\.kube\\config";
public static void getAllPodList() throws IOException, ApiException {
ApiClient apiClient = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
// new a CoreV1Api
CoreV1Api api = new CoreV1Api(apiClient);
// invokes the CoreV1Api client
V1PodList podList = api.listPodForAllNamespaces().execute();
for (V1Pod item : podList.getItems()) {
String result = removePrefixAndLastTwoDashes(item.getMetadata().getName());
if (result.equals("ds-base-web")) {
System.out.println(result);
}
}
}
/**
* 功能:去掉前缀和最后一个两个-
*
* @param input
* @return
*/
public static String removePrefixAndLastTwoDashes(String input) {
// 去掉开头的default:
String trimmed = input.replaceFirst("^default:", "");
// 去掉最后两个以-开头的字符串
Pattern pattern = Pattern.compile("-[^-]+(-[^-]+)?$");
Matcher matcher = pattern.matcher(trimmed);
if (matcher.find()) {
return trimmed.substring(0, trimmed.length() - matcher.group().length());
}
return trimmed;
}
public static void main(String[] args) throws IOException, ApiException {
getAllPodList();
}
}