Kubernetes official java client 8: fluent style

itread01 2021-01-14 14:13:00
kubernetes official java client fluent


### Welcome to my GitHub[https://github.com/zq2599/blog_demos](https://github.com/zq2599/blog_demos) Content : All original articles classified summary and supporting original code , involve Java、Docker、Kubernetes、DevOPS etc. ;### Survey 1. This article is about 《Kubernetes official java Client 》 The eighth part of the series , As mentioned below java The client refers to client-jar.jar;2. above [《Kubernetes official java Client 7 :patch operation 》](https://blog.csdn.net/boling_cavalry/article/details/107885697) Knowledge points involved 、 Code 、 There are too many operations , It is a great torment to the author and the reader , When it comes to this article, let's relax , Write some simple and fluent code , Understanding java Client to fluent style Programming support , And the verification operation after coding is also very simple ;### About fluent styel1. Also known as fluid coding, fluent programming, It's a style that enhances code readability , Make reading code more natural and fluent , The feature is that the function returns the relevant type , Connect the calls of multiple functions before and after .2. About fluent style You can refer to Martin Flowler On 2005 Articles published in , The address is :https://martinfowler.com/bliki/FluentInterface.html , Use fluent style The code comparison before and after is shown in the figure below :![3.](https://img2020.cnblogs.com/other/485422/202101/485422-20210114075835272-1049357253.png) ### Source code download 1. If you don't want to code , Can be in GitHub Download all the source code , The address and link information is shown in the table below (https://github.com/zq2599/blog_demos):| Name | Link to | Note || :-------- | :----| :----|| Project home page | https://github.com/zq2599/blog_demos | The project is in GitHub Home page on || git Warehouse address (https)| https://github.com/zq2599/blog_demos.git | The warehouse address of the project source code ,https Agreement || git Warehouse address (ssh)| [email protected]:zq2599/blog_demos.git | The warehouse address of the project source code ,ssh Agreement |2. This git There are multiple folders in the project , The application of this chapter is in kubernetesclient Under folder , As shown in the red box below :![ Insert picture description here ](https://img2020.cnblogs.com/other/485422/202101/485422-20210114075835936-1918120388.png)### Overview of actual combat steps 1. In the parent project kubernetesclient Next, create a new one called fluent The sub project of ;2. fluent There is only one class in the project FluentStyleApplication, Started main Methods and fluent style All of the code in this class ;3. FluentStyleApplication.java Provide four web Interface , The functions are : newly build namespace、 newly build deployment、 newly build service、 Delete all new resources created by the previous three interfaces ;4. fluent After the project coding is completed , You don't need to make an image to deploy in kubernetes Inside the environment , But as an ordinary SpringBoot Apply to find a java Just start the environment , And [《Kubernetes official java Client three : External applications 》](https://blog.csdn.net/boling_cavalry/article/details/107528068) The deployment and startup of this article are consistent ;5. Call each interface in turn , Verify that the function is as expected ;### Code 1. In the parent project kubernetesclient Next, create a new one called fluent Of maven Sub project ,pom.xml The content is as follows , It should be noted to exclude spring-boot-starter-json, Please refer to [《Kubernetes official java Client 2 : Serialization and deserialization issues 》](https://blog.csdn.net/boling_cavalry/article/details/107503695):```xml```2. newly build FluentStyleApplication.java, First , This class acts as the startup class , Want to have main Method :```javapublic static void main(String[] args) { SpringApplication.run(FluentStyleApplication.class, args);}```3. Define constants NAMESPACE As a result of the actual combat namespace:```javaprivate final static String NAMESPACE = "fluent";```4. use @PostConstruct To modify setDefaultApiClient Method , Make it execute once during instantiation , There are some global initialization settings , Be careful kubeConfigPath Variable corresponding to config The file path should be correct :```java/** * The global setting of presupposition * @return * @throws Exception */ @PostConstruct private void setDefaultApiClient() throws Exception { // Deposit K8S Of config The full path of Archives String kubeConfigPath = "/Users/zhaoqin/temp/202007/05/config"; // With config Established as an input client thing , You can access K8S Of API Server ApiClient client = ClientBuilder .kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))) .build(); // Can print and API Server Details of the request response between , Careful use of production environment client.setDebugging(true); // Create an operation class Configuration.setDefaultApiClient(client); }```5. The next step is to build namespace Of web Service , As shown below , Because of namespace stay kubernetes Of apiVersion yes v1, So it's built on V1Namespace For example :```java @RequestMapping(value = "/fluent/createnamespace") public V1Namespace createnamespace() throws Exception { V1Namespace v1Namespace = new V1NamespaceBuilder() .withNewMetadata() .withName(NAMESPACE) .addToLabels("label1", "aaa") .addToLabels("label2", "bbb") .endMetadata() .build(); return new CoreV1Api().createNamespace(v1Namespace, null, null, null); }```6. For a clearer picture fluent style effect , Connect the above code to create namespace Of yaml The contents of the files are compared together , As shown in the figure below , In contrast to yaml Files can write the code :![ Insert picture description here ](https://img2020.cnblogs.com/other/485422/202101/485422-20210114075837023-1626431244.png)7. The next step is to build service Code for , In order to make peace with yaml Corresponding to , The code is specially indented :```java @RequestMapping(value = "/fluent/createservice") public V1Service createservice() throws Exception { V1Service v1Service = new V1ServiceBuilder() // meta Set .withNewMetadata() .withName("nginx") .endMetadata() // spec Set .withNewSpec() .withType("NodePort") .addToPorts(new V1ServicePort().port(80).nodePort(30103)) .addToSelector("name", "nginx") .endSpec() .build(); return new CoreV1Api().createNamespacedService(NAMESPACE, v1Service, null, null, null); }```8. establish deployment The code of is as follows , It's more complicated because of the content , Please note , Because of deployment stay kubernetes Of apiVersion yes extensions/v1beta1, So it's built on ExtensionsV1beta1Deployment For example :```java @RequestMapping(value = "/fluent/createdeployment") public ExtensionsV1beta1Deployment createdeployment() throws Exception { ExtensionsV1beta1Deployment v1Deployment = new ExtensionsV1beta1DeploymentBuilder() // meta Set .withNewMetadata() .withName("nginx") .endMetadata() // spec Set .withNewSpec() .withReplicas(1) // spec Of templat .withNewTemplate() // template Of meta .withNewMetadata() .addToLabels("name", "nginx") .endMetadata() // template Of spec .withNewSpec() .addNewContainer() .withName("nginx") .withImage("nginx:1.18.0") .addToPorts(new V1ContainerPort().containerPort(80)) .endContainer() .endSpec() .endTemplate() .endSpec() .build(); return new ExtensionsV1beta1Api().createNamespacedDeployment(NAMESPACE, v1Deployment, null, null, null); } ```9. As you can see from the above code ,withXXX and endXXX It's in pairs , Please pay attention not to omit when programming endXXX, I'm writing withXXX At the same time endXXX Write it down ;10. The last way is to clean up all the resources , What was built before deployment、service、namespace It's all cleaned up here at once , I found an embarrassing situation in the actual operation : Delete deployment and namespace When , Send to API Server All the delete requests received the successful response of the operation , but kubernetes The client threw an exception while deserializing the response content ( The log shows the details ), My ability is limited and I haven't found a solution yet , So you can only use try catch To avoid the whole method throwing exception , Fortunately kubernetes In fact, it has been deleted successfully , It doesn't matter much :```java @RequestMapping(value = "/fluent/clear") public String clear() throws Exception { // Delete deployment try { new ExtensionsV1beta1Api().deleteNamespacedDeployment("nginx", NAMESPACE, null, null, null, null, null, null); } catch (Exception e) { log.error("delete deployment error", e); } CoreV1Api coreV1Api = new CoreV1Api(); // Delete service coreV1Api.deleteNamespacedService("nginx", NAMESPACE, null, null, null, null, null, null); // Delete namespace try { coreV1Api.deleteNamespace(NAMESPACE, null, null, null, null, null, null); } catch (Exception e) { log.error("delete namespace error", e); } return "clear finish, " + new Date(); }```11. The encoding is complete , Start fluent engineering , Next, start to verify whether the function is normal ;### Verification 1. Will fluent The project is directly in IEDA The environment starts ;2. Browser access :http://localhost:8080/fluent/createnamespace , The page will show API Server The integrity of the return namespace Information :![ Insert picture description here ](https://img2020.cnblogs.com/other/485422/202101/485422-20210114075838391-378561896.png)3. Browser access :http://localhost:8080/fluent/createservice , The page will show API Server The integrity of the return service Information :![ Insert picture description here ](https://img2020.cnblogs.com/other/485422/202101/485422-20210114075839563-1951181876.png)4. Browser access :http://localhost:8080/fluent/createdeployment , The page will show API Server The integrity of the return deployment Information :![ Insert picture description here ](https://img2020.cnblogs.com/other/485422/202101/485422-20210114075841320-1253858470.png)5. Verify that the services created by the previous interfaces are available , Here I am kubernetes Of IP The address is 192.168.50.135, So visit :http://192.168.50.135:30103 , It can be displayed normally nginx Home :![ Insert picture description here ](https://img2020.cnblogs.com/other/485422/202101/485422-20210114075841857-1188705843.png)6. SSH Log in kubernetes Server view , Through kubernetes Of java All the resources created by the client are normal :![ Insert picture description here ](https://img2020.cnblogs.com/other/485422/202101/485422-20210114075842643-1863580468.png)7. After verification , Browser access :http://localhost:8080/fluent/clear , You can clean up the resources created by the previous three interfaces ;- thus , Based on fluent style call java The actual combat of the client is completed , I hope you can use this style skillfully API call , Make coding easier and smoother , By the way , Next, I'll continue to do some simple and easy operations , The goal is to be familiar with java Common client operations ;### You're not alone , Xinchen's original works are accompanied all the way 1. [Java series ](https://xinchen.blog.csdn.net/article/details/105068742)2. [Spring series ](https://xinchen.blog.csdn.net/article/details/105086498)3. [Docker series ](https://xinchen.blog.csdn.net/article/details/105086732)4. [kubernetes series ](https://xinchen.blog.csdn.net/article/details/105086794)5. [ Database + Intermediary software series ](https://xinchen.blog.csdn.net/article/details/105086850)6. [DevOps series ](https://xinchen.blog.csdn.net/article/details/105086920)### Welcome to the public account : Programmer Xinchen > Wechat search 「 Programmer Xinchen 」, I'm Xinchen , Looking forward to traveling with you Java The world ...[https://github.com/zq2599/blog_demos](https://github.com/zq2599/blo
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210114114646599d.html

  1. Spring boot static resource configuration principle (step by step source analysis, detailed and easy to understand)
  2. 400万Docker镜像中,51%的镜像存在高危漏洞
  3. Head first design pattern -- 10. Iterator pattern
  4. A few pictures, take down the HTTPS
  5. Simple use of pyecharts module
  6. [azure redis cache] discussion on the functionality of azure redis
  7. Installation of SVN under Linux
  8. Sorting out knowledge points of MySQL Cluster
  9. rocketmq-cpp-client Visual Studio 2019 编译
  10. rocketmq-cpp-client Visual Studio 2019 编译
  11. RBAC authorization mode of k8s
  12. Remember to use it once Asp.Net The development process of core webapi 5.0 + dapper + MySQL + redis + docker
  13. Java Concurrent Programming points
  14. Explain Java I / O flow in detail
  15. Linux system builds springboot project environment and deploys it
  16. Easy to understand JS object-oriented, by the way understand prototype and__ proto__
  17. Summary of java basic knowledge
  18. . net cloud native architect training camp (module 2 basic consolidation rabbitmq mastransit detailed explanation) - learning notes
  19. The architecture of MySQL
  20. MySQL security management, database maintenance and performance improvement
  21. Redis basic command
  22. Summary of MySQL articles
  23. 2、 Create k8s cluster in 5 seconds
  24. data自定义属性在jQuery中的用法
  25. Linux常见解压缩
  26. Detailed explanation of HBase basic principle
  27. 1、 Why and how to learn k8s
  28. Java advanced (29) -- HashMap set
  29. java中大文件上传
  30. Weblogic 2017-3248 analysis of Java Security
  31. Kubernetes official java client 8: fluent style
  32. Explain the function of thread pool and how to use it in Java
  33. Programming software tutorial video Encyclopedia: C + + / Java / Python / assembly / easy language (with tutorial)
  34. Description of dependency problem after javacv is updated to 1.5. X and how to reduce the size of dependency package
  35. Java reflection & dynamic agent
  36. Building Apache 2.4 + php7 + mysql8 in centos7 environment
  37. Summary of Java multithreading (1)
  38. Oracle AWR report generation
  39. Four magic functions of mybatis, don't step on the pit!
  40. A 16-year-old high school student successfully transplanted Linux to iPhone and posted a detailed guide
  41. Centos7 one click installation of JDK1.8 shell script
  42. Mounting of file system in Linux (centos7)
  43. How does serverless deal with the resource supply demand of k8s in the offline scenario
  44. Detailed explanation of HBase basic principle
  45. Spring security oauth2.0 authentication and authorization 4: distributed system authentication and authorization
  46. Redis performance Part 5 redis buffer
  47. JavaScript this keyword
  48. Summary of Java multithreading (3)
  49. Sentry(v20.12.1) K8S 云原生架构探索, SENTRY FOR JAVASCRIPT 手动捕获事件基本用法
  50. Sentry(v20.12.1) K8S 云原生架构探索, SENTRY FOR JAVASCRIPT 手动捕获事件基本用法
  51. (10) Spring from the beginning to the end
  52. Summary of Java multithreading (2)
  53. Spring source notes! From the introduction to the source code, let you really understand the source code
  54. A stormy sunny day
  55. Zookeeper (curator), the implementation of distributed lock
  56. Show the sky! Tencent T4's core Java Dictionary (framework + principle + Notes + map)
  57. Spring boot project, how to gracefully replace the blank value in the interface parameter with null value?
  58. Spring boot project, how to gracefully replace the blank value in the interface parameter with null value?
  59. docker+mysql集群+读写分离+mycat管理+垂直分库+负载均衡
  60. docker+mysql集群+读写分离+mycat管理+垂直分库+负载均衡