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.File; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class K8sClientTest { public static void getAllPodList() throws IOException, ApiException { //Master /root/.kube/config文件拷贝过来 String kubeConfigPath = PathKit.getRootClassPath() + "\\.kube\\config"; if (!new File(kubeConfigPath).exists()) { System.out.println("kubeConfig不存在,跳过"); return; } 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(); } }