如何使用 fabric8 kubernetes Java 和 Scala 客户端 API 在容器上设置资源需求

eje*_*eje 3 java client scala fabric8 kubernetes

fabric8 kubernetes Java 和 Scala 客户端 API 非常适合与 kubernetes(或 OpenShift)对话,但其文档非常稀少。向在 Kubernetes pod 中运行的容器添加资源需求的代码示例是什么?

eje*_*eje 5

如果您使用的是面向 Java 和 Scala 的fabric8 kubernetes-client API,这里是一段代码,演示了如何向在 pod 中运行的容器添加资源需求。此代码是从 Scala 复制的,但 Java 代码非常相似:

// other fabric8 imports not included; just focusing on resource
// requirements logic in this example
import io.fabric8.kubernetes.api.model.Quantity
import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder

// Use Java style Map (as opposed to Scala's Map class)
val reqMap: java.util.Map[String, Quantity] =
  new java.util.HashMap[String, Quantity]()

// add CPU and memory requirements to the map
reqMap.put("cpu", new Quantity("1"))
reqMap.put("memory", new Quantity("1500Mi"))

// Build a ResourceRequirements object from the map
val reqs = new ResourceRequirementsBuilder()
  .withRequests(reqMap)
  .build()

// pass the ResourceRequirements object to the container spec
val pod = new PodBuilder()
  .withNewMetadata()
  .withName(podName)
  .endMetadata()
  .withNewSpec()
  .withRestartPolicy("OnFailure")
  .addNewContainer()
  .withName(containerName)
  .withImage(containerImage)
  .withImagePullPolicy("Always")
  .withResources(reqs)            // <-- resource reqs here
  .withCommand(commandName)
  .withArgs(commandArguments)
  .endContainer()
  .endSpec()
  .build()

// create the new pod with resource requirements via the 
// fabric8 kube client:
client.pods().inNamespace(nameSpace).withName(podName).create(pod)
Run Code Online (Sandbox Code Playgroud)