RESTClient 底层原理
RESTClient 概述
RESTClient 是 client-go 最底层的 HTTP 客户端,Clientset 和 DynamicClient 都基于它构建。
直接使用 RESTClient
go
import (
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
config, _ := clientcmd.BuildConfigFromFlags("", os.Getenv("KUBECONFIG"))
// 创建 RESTClient
restClient, err := rest.RESTClientFor(&rest.Config{
Host: config.Host,
APIPath: "/api",
ContentConfig: rest.ContentConfig{
GroupVersion: &corev1.SchemeGroupVersion,
NegotiatedSerializer: scheme.Codecs.WithoutConversion(),
},
BearerToken: config.BearerToken,
TLSClientConfig: config.TLSClientConfig,
})
// 发起请求
result := &corev1.PodList{}
err = restClient.Get().
Namespace("default").
Resource("pods").
VersionedParams(&metav1.ListOptions{
LabelSelector: "app=nginx",
}, scheme.ParameterCodec).
Do(ctx).
Into(result)
// 获取单个资源
pod := &corev1.Pod{}
err = restClient.Get().
Namespace("default").
Resource("pods").
Name("my-pod").
Do(ctx).
Into(pod)请求构建器
go
// 完整的请求构建链
restClient.Verb("GET").
AbsPath("/apis/apps/v1").
Namespace("default").
Resource("deployments").
Name("my-app").
SubResource("scale").
Param("pretty", "true").
Body(scaleObj).
Timeout(30 * time.Second).
Do(ctx).
Into(result)速率限制
go
// 配置客户端速率限制
config.QPS = 100 // 每秒 100 个请求
config.Burst = 200 // 突发 200 个请求
// 自定义速率限制器
import "golang.org/x/time/rate"
config.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(100, 200)连接池配置
go
config.Transport = &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
}