一、环境要求
k8s必须安装metric-server组件
二、使用步骤
1.pom配置
<dependency>
<groupId>io.kubernetes</groupId>
<artifactId>client-java</artifactId>
<version>12.0.0</version>
</dependency>
官方网址:GitHub - kubernetes-client/java: Official Java client library for kubernetes
2.java代码
ApiClient client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader("D:\\test\\kubernetes\\admin.conf"))).build();
Configuration.setDefaultApiClient(client); //admin.conf是k8s生成可以拉到本地,或者此处可以使用token连接方式,参见官方demo
GenericKubernetesApi<NodeMetrics, NodeMetricsList> nodeMetricsListGenericKubernetesApi = new GenericKubernetesApi<>(
NodeMetrics.class,
NodeMetricsList.class,
"metrics.k8s.io",
"v1beta1",
"nodes",
client);
NodeMetricsList nodeMetricsList = nodeMetricsListGenericKubernetesApi.list().getObject();
HashMap<String, Map<String, String>> usages = new HashMap<>();
for (NodeMetrics item : nodeMetricsList.getItems()) {
String name = item.getMetadata().getName();
Map<String, Quantity> usage = item.getUsage();
Map<String, String> quantity = new HashMap<>();
for (String s : usage.keySet()) {
Quantity quantity1 = usage.get(s);
String s1 = quantity1.toSuffixedString();
quantity.put(s,s1);
}
usages.put(name,quantity);
}
CoreV1Api api = new CoreV1Api();
V1NodeList viNodeList = api.listNode(null, false, null, null, null, 0, null, null, 0, false);
List<Cllocata> cList = new ArrayList<>();
for (V1Node v1Node :viNodeList.getItems()){
Cllocata cllocata = new Cllocata();
V1NodeStatus v1NodeStatus = v1Node.getStatus();
List<V1NodeAddress> v1NodeAddresss = v1NodeStatus.getAddresses();
for (V1NodeAddress v1NodeAddress:v1NodeAddresss){
String type = v1NodeAddress.getType();
String address = v1NodeAddress.getAddress();
if("InternalIP".equals(type)){
cllocata.setIp(address);
}else if("Hostname".equals(type)){
cllocata.setName(address);
}
}
Map<String, Quantity> map = v1NodeStatus.getAllocatable();
cllocata.setCpu(map.get("cpu").toSuffixedString());
cllocata.setMemory(map.get("memory").toSuffixedString());
cList.add(cllocata);
}
Map<String,Object> cMap = new HashMap<>();
cMap.put("component", ComponentEnum.K8S);
List<SystemAlarmParams> sapList = systemAlarmParamsMapper.selectByMap(cMap);
for (Cllocata cllocata :cList){
Map<String,String> map = usages.get(cllocata.getName());
if(map != null){
String cpu = map.get("cpu");
cpu = cpu.replace("n","");
String memory = map.get("memory");
memory = memory.replace("Ki","");
String aCpu = cllocata.getCpu();
String aMemory = cllocata.getMemory();
aMemory = aMemory.replace("Ki","");
int pCpu = Math.round(100*Long.parseLong(cpu)/1000/1000/1000/Long.parseLong(aCpu));
int pMemory = Math.round(100*Long.parseLong(memory)/Long.parseLong(aMemory));
String ip = cllocata.getIp();
}
}
三、其他
与此开源包相似的还有fabri-k8s?GitHub - fabric8io/kubernetes-client: Java client for Kubernetes & OpenShift
|