1.pom文件中添加
<dependency> <groupId>io.fabric8groupId> <artifactId>kubernetes-apiartifactId> <version>2.2.176version> dependency> <dependency> <groupId>net.eusashead.hateoasgroupId> <artifactId>spring-responseentitybuilderartifactId> <version>1.1.0.RELEASEversion> dependency>
2.java代码
public class KubernetesApiUtil {
//多个环境的k8,所以用map存储
private static Map
private KubernetesClient client;
private String hpaUrl;
private String nameSpace;
//构造函数,创建连接实例
private KubernetesApiUtil (String k8sMaterUrl){
String masterUrl = k8sMaterUrl.endsWith("/")?k8sMaterUrl:k8sMaterUrl+"/";
Config config = new ConfigBuilder().withMasterUrl(masterUrl).build();
config.setRequestTimeout(2000);
this.client = new DefaultKubernetesClient(config);
this.nameSpace = "cscloud-test";
this.hpaUrl = masterUrl+"apis/autoscaling/v1/namespaces/{namespace}/horizontalpodautoscalers/{name}";
}
//获取连接实例
static final KubernetesApiUtil getInstances(String k8sMaterUrl){
if(!k8sMap.containsKey(k8sMaterUrl)){
KubernetesApiUtil kubernetesApiUtil = new KubernetesApiUtil(k8sMaterUrl);
k8sMap.put(k8sMaterUrl, kubernetesApiUtil);
}
return k8sMap.get(k8sMaterUrl);
}
/*
* kus分配端口映射Map
*/
private List
/*
* 创建HPA
*/
public ResponseEntity createHpa(String yaml){
try {
String hpaPostData = this.convertYamlToJson(yaml);
ResponseEntity
// int retCode =(resonseEntity !=null && resonseEntity.getStatusCode().equals(HttpStatus.CREATED))?1:-1;
return resonseEntity;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
/*
* 创建RC
*/
public String createRC(String yaml){
Controller ctrl = new Controller(client);
ctrl.setRecreateMode(true);
try {
return ctrl.applyYaml(yaml);
} catch (Exception e) {
return null;
}
}
/*
* 调用restful接口
*
*/
public ResponseEntity
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity
if (method.equalsIgnoreCase("delete")) {
return restTemplate.exchange(this.hpaUrl, HttpMethod.DELETE, requestEntity, String.class,this.nameSpace,param);
}else if (method.equalsIgnoreCase("create")) {
return restTemplate.exchange(this.hpaUrl, HttpMethod.POST, requestEntity, String.class,this.nameSpace,param);
}else if (method.equalsIgnoreCase("get")) {
return restTemplate.exchange(this.hpaUrl, HttpMethod.GET, requestEntity, String.class,this.nameSpace,param);
}
return null;
}
/*
* 将yamlStr转为json
*/
public String convertYamlToJson(String yamlStr){
Yaml yaml = new Yaml();
Map
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject.toString();
}
}
其他:https://www.2cto.com/kf/201708/664162.html