欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Go語言開發(fā)k8s之Service操作解析

 更新時間:2023年06月21日 14:13:58   作者:開發(fā)運維玄德公  
這篇文章主要為大家介紹了Go語言開發(fā)k8s之Service操作解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

1. 結(jié)構(gòu)體

1.1 ServiceList

所在包:"k8s.io/api/core/v1"

type ServiceList struct {
    v1.TypeMeta `json:",inline"`
    v1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    Items           []Service `json:"items" protobuf:"bytes,2,rep,name=items"`
}

其中Items下各元素的service結(jié)構(gòu)體如下:

1.2 Service

所在包:"k8s.io/api/core/v1"

type Service struct {
    v1.TypeMeta   `json:",inline"`
    v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    Spec              ServiceSpec   `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
    Status            ServiceStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

其中TypeMeta、ObjectMeta ServiceSpec ServiceStatus結(jié)構(gòu)體如下:

1.3 TypeMeta

所在包:"k8s.io/apimachinery/pkg/apis/meta/v1"

type TypeMeta struct {
    Kind       string `json:"kind,omitempty" protobuf:"bytes,1,opt,name=kind"`
    APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,2,opt,name=apiVersion"`
}

對應(yīng)k8s的yaml文件如下部分:

apiVersion: v1
kind: Service

1.4 ObjectMeta

所在包:"k8s.io/apimachinery/pkg/apis/meta/v1"

type ObjectMeta struct {
    Name                       string               `json:"name,omitempty" protobuf:"bytes,1,opt,name=name"`
    GenerateName               string               `json:"generateName,omitempty" protobuf:"bytes,2,opt,name=generateName"`
    Namespace                  string               `json:"namespace,omitempty" protobuf:"bytes,3,opt,name=namespace"`
    SelfLink                   string               `json:"selfLink,omitempty" protobuf:"bytes,4,opt,name=selfLink"`
    UID                        types.UID            `json:"uid,omitempty" protobuf:"bytes,5,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"`
    ResourceVersion            string               `json:"resourceVersion,omitempty" protobuf:"bytes,6,opt,name=resourceVersion"`
    Generation                 int64                `json:"generation,omitempty" protobuf:"varint,7,opt,name=generation"`
    CreationTimestamp          Time                 `json:"creationTimestamp,omitempty" protobuf:"bytes,8,opt,name=creationTimestamp"`
    DeletionTimestamp          *Time                `json:"deletionTimestamp,omitempty" protobuf:"bytes,9,opt,name=deletionTimestamp"`
    DeletionGracePeriodSeconds *int64               `json:"deletionGracePeriodSeconds,omitempty" protobuf:"varint,10,opt,name=deletionGracePeriodSeconds"`
    Labels                     map[string]string    `json:"labels,omitempty" protobuf:"bytes,11,rep,name=labels"`
    Annotations                map[string]string    `json:"annotations,omitempty" protobuf:"bytes,12,rep,name=annotations"`
    OwnerReferences            []OwnerReference     `json:"ownerReferences,omitempty" patchStrategy:"merge" patchMergeKey:"uid" protobuf:"bytes,13,rep,name=ownerReferences"`
    Finalizers                 []string             `json:"finalizers,omitempty" patchStrategy:"merge" protobuf:"bytes,14,rep,name=finalizers"`
    ManagedFields              []ManagedFieldsEntry `json:"managedFields,omitempty" protobuf:"bytes,17,rep,name=managedFields"`
}

對應(yīng)k8s的yml文件中如下部分

metadata:
  ……

代碼中實例化示例如下:

        ObjectMeta: metaV1.ObjectMeta{
            Name: "nginx",
            Labels: map[string]string{
                "app":"nginx",
            },
        },

1.5 ServiceSpec

所在包:"k8s.io/api/core/v1"

type ServiceSpec struct {
    Ports                         []ServicePort                     `json:"ports,omitempty" patchStrategy:"merge" patchMergeKey:"port" protobuf:"bytes,1,rep,name=ports"`
    Selector                      map[string]string                 `json:"selector,omitempty" protobuf:"bytes,2,rep,name=selector"`
    ClusterIP                     string                            `json:"clusterIP,omitempty" protobuf:"bytes,3,opt,name=clusterIP"`
    ClusterIPs                    []string                          `json:"clusterIPs,omitempty" protobuf:"bytes,18,opt,name=clusterIPs"`
    Type                          ServiceType                       `json:"type,omitempty" protobuf:"bytes,4,opt,name=type,casttype=ServiceType"`
    ExternalIPs                   []string                          `json:"externalIPs,omitempty" protobuf:"bytes,5,rep,name=externalIPs"`
    SessionAffinity               ServiceAffinity                   `json:"sessionAffinity,omitempty" protobuf:"bytes,7,opt,name=sessionAffinity,casttype=ServiceAffinity"`
    LoadBalancerIP                string                            `json:"loadBalancerIP,omitempty" protobuf:"bytes,8,opt,name=loadBalancerIP"`
    LoadBalancerSourceRanges      []string                          `json:"loadBalancerSourceRanges,omitempty" protobuf:"bytes,9,opt,name=loadBalancerSourceRanges"`
    ExternalName                  string                            `json:"externalName,omitempty" protobuf:"bytes,10,opt,name=externalName"`
    ExternalTrafficPolicy         ServiceExternalTrafficPolicyType  `json:"externalTrafficPolicy,omitempty" protobuf:"bytes,11,opt,name=externalTrafficPolicy"`
    HealthCheckNodePort           int32                             `json:"healthCheckNodePort,omitempty" protobuf:"bytes,12,opt,name=healthCheckNodePort"`
    PublishNotReadyAddresses      bool                              `json:"publishNotReadyAddresses,omitempty" protobuf:"varint,13,opt,name=publishNotReadyAddresses"`
    SessionAffinityConfig         *SessionAffinityConfig            `json:"sessionAffinityConfig,omitempty" protobuf:"bytes,14,opt,name=sessionAffinityConfig"`
    IPFamilies                    []IPFamily                        `json:"ipFamilies,omitempty" protobuf:"bytes,19,opt,name=ipFamilies,casttype=IPFamily"`
    IPFamilyPolicy                *IPFamilyPolicy                   `json:"ipFamilyPolicy,omitempty" protobuf:"bytes,17,opt,name=ipFamilyPolicy,casttype=IPFamilyPolicy"`
    AllocateLoadBalancerNodePorts *bool                             `json:"allocateLoadBalancerNodePorts,omitempty" protobuf:"bytes,20,opt,name=allocateLoadBalancerNodePorts"`
    LoadBalancerClass             *string                           `json:"loadBalancerClass,omitempty" protobuf:"bytes,21,opt,name=loadBalancerClass"`
    InternalTrafficPolicy         *ServiceInternalTrafficPolicyType `json:"internalTrafficPolicy,omitempty" protobuf:"bytes,22,opt,name=internalTrafficPolicy"`
}

對應(yīng)原生k8s創(chuàng)建service的 yml文件中spec的內(nèi)容示例如下:(這一部分也是我們主要填寫的)

spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 80
    nodePort: 30500
  selector:
    app: nginx

代碼示例如下:

        Spec: coreV1.ServiceSpec{
            Type: coreV1.ServiceTypeNodePort,
            Selector: map[string]string{
                "app":"nginx",
            },
            Ports: []coreV1.ServicePort{
                {
                    Port: 80,
                    Protocol: coreV1.ProtocolTCP,
                    NodePort: nodePort,
                },
            },
        }

1.6 ServiceStatus

所在包:"k8s.io/api/core/v1"

type ServiceStatus struct {
    LoadBalancer LoadBalancerStatus `json:"loadBalancer,omitempty" protobuf:"bytes,1,opt,name=loadBalancer"`
    Conditions   []v1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,2,rep,name=conditions"`
}

service 的狀態(tài),這個不用過多操作。

1.7 對照yml文件示例

附原生k8s集群上一個service 信息,大家可以對照理解一下以上結(jié)構(gòu)體

apiVersion: v1
kind: Service
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["10.10.117.53"],"port":30051,"protocol":"TCP","serviceName":"liubei:nginx","allNodes":true}]'
  creationTimestamp: "2022-09-29T07:01:01Z"
  labels:
    app: nginx
  name: nginx
  namespace: liubei
  resourceVersion: "19646213"
  selfLink: /api/v1/namespaces/liubei/services/nginx
  uid: 7d05764c-87a7-46d1-8e4f-bed136755fb9
spec:
  clusterIP: 10.1.101.241
  clusterIPs:
  - 10.1.101.241
  externalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - nodePort: 30051
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: nginx
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {}

2. Get List

語法

func (ServiceInterface) List(ctx context.Context, opts v1.ListOptions) (*v1.ServiceList, error)
  • 語法示例
serviceList,err = clientSet.CoreV1().Services(namespaceName).List(context.TODO(),metaV1.ListOptions{})

完整示例

  • 創(chuàng)建函數(shù)
package crowK8S
import (
    "context"
    "fmt"
    coreV1 "k8s.io/api/core/v1"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func GetServiceList(clientSet *kubernetes.Clientset,namespaceName string) (serviceList *coreV1.ServiceList,err error) {
    serviceList,err = clientSet.CoreV1().Services(namespaceName).List(context.TODO(),metaV1.ListOptions{})
    if err != nil {
        return serviceList,err
    }
    return serviceList,nil
}
  • 調(diào)用
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    serviceList,err := crowK8S.GetServiceList(clientSet,"kube-system")
    for _,serviceInfo := range serviceList.Items{
        fmt.Println(serviceInfo.Name)
    }
}

輸出

kube-dns
metrics-server

3. Create

語法

func (ServiceInterface) Create(ctx context.Context, service *v1.Service, opts v1.CreateOptions) (*v1.Service, error)
  • 代碼示例
serviceInfo,err = clientSet.CoreV1().Services(namespace).Create(context.TODO(),service,metaV1.CreateOptions{})

完整示例

  • yml文件對照

以下是邊這個yml文件為例,我們就照著這個內(nèi)容寫代碼:

apiVersion: v1
kind: Service
metadata:
  name: nginx
  namespace: test
  labels:
    app: nginx
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 80
    nodePort: 30500
  selector:
    app: nginx
  • 定義函數(shù)
func CreateService(clientSet *kubernetes.Clientset,namespaceName string) (serviceInfo *coreV1.Service,err error) {
    namespace := namespaceName
    service := &coreV1.Service{
        ObjectMeta: metaV1.ObjectMeta{
            Name: "nginx",
            Labels: map[string]string{
                "app":"nginx",
            },
        },
        Spec: coreV1.ServiceSpec{
            Type: coreV1.ServiceTypeNodePort,
            Selector: map[string]string{
                "app":"nginx",
            },
            Ports: []coreV1.ServicePort{
                {
                    Port: 80,
                    Protocol: coreV1.ProtocolTCP,
                    NodePort: 30050,
                },
            },
        },
    }
    serviceInfo,err = clientSet.CoreV1().Services(namespace).Create(context.TODO(),service,metaV1.CreateOptions{})
    return serviceInfo,nil
}
  • 調(diào)用
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    serviceInfo,err := crowK8S.CreateService(clientSet ,"liubei")
    fmt.Println(serviceInfo)
}
  • 結(jié)果輸出

本來是一個json字串,以下是我格式化之后貼上來的:

{
    ObjectMeta: {
        nginx liubei / api / v1 / namespaces / liubei / services / nginx 7 d05764c - 87 a7 - 46 d1 - 8e4 f - bed136755fb9 19389876 0 2022 - 09 - 29 15: 01: 01 + 0800 CST < nil > < nil > map[app: nginx] map[][][][{
            ___6go_build_main_go.exe Update v1 2022 - 09 - 29 15: 01: 01 + 0800 CST FieldsV1 {
                "f:metadata": {
                    "f:labels": {
                        ".": {},
                        "f:app": {}
                    }
                },
                "f:spec": {
                    "f:externalTrafficPolicy": {},
                    "f:ports": {
                        ".": {},
                        "k:{\"port\":80,\"protocol\":\"TCP\"}": {
                            ".": {},
                            "f:nodePort": {},
                            "f:port": {},
                            "f:protocol": {},
                            "f:targetPort": {}
                        }
                    },
                    "f:selector": {
                        ".": {},
                        "f:app": {}
                    },
                    "f:sessionAffinity": {},
                    "f:type": {}
                }
            }
        }]
    },
    Spec: ServiceSpec {
        Ports: [] ServicePort {
            ServicePort {
                Name: ,
                Protocol: TCP,
                Port: 80,
                TargetPort: {
                    0 80
                },
                NodePort: 30050,
                AppProtocol: nil,
            },
        },
        Selector: map[string] string {
            app: nginx,
        },
        ClusterIP: 10.1 .101 .241,
        Type: NodePort,
        ExternalIPs: [],
        SessionAffinity: None,
        LoadBalancerIP: ,
        LoadBalancerSourceRanges: [],
        ExternalName: ,
        ExternalTrafficPolicy: Cluster,
        HealthCheckNodePort: 0,
        PublishNotReadyAddresses: false,
        SessionAffinityConfig: nil,
        IPFamilyPolicy: * SingleStack,
        ClusterIPs: [10.1 .101 .241],
        IPFamilies: [IPv4],
        AllocateLoadBalancerNodePorts: nil,
        LoadBalancerClass: nil,
        InternalTrafficPolicy: nil,
    },
    Status: ServiceStatus {
        LoadBalancer: LoadBalancerStatus {
            Ingress: [] LoadBalancerIngress {},
        },
        Conditions: [] Condition {},
    },
}

4. Get Service

語法示例

  • 創(chuàng)建函數(shù)
func GetService(clientSet *kubernetes.Clientset,namespaceName string,serviceName string) (serviceInfo *coreV1.Service,err error) {
    serviceInfo,err = clientSet.CoreV1().Services(namespaceName).Get(context.TODO(),serviceName,metaV1.GetOptions{})
    if err != nil {
        return serviceInfo,err
    }
    return serviceInfo,nil
}
  • 調(diào)用
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    serviceInfo,err := crowK8S.GetService(clientSet ,"liubei","nginx")
    fmt.Println(serviceInfo)
}

結(jié)果顯示

同創(chuàng)建時的結(jié)果

5. Update Service

語法

  • 語法
func (ServiceInterface) Update(ctx context.Context, service *v1.Service, opts v1.UpdateOptions) (*v1.Service, error)
  • 語法示例
serviceInfo,err = clientSet.CoreV1().Services(namespaceName).Update(context.TODO(),service,metaV1.UpdateOptions{})

完整示例

  • 創(chuàng)建函數(shù)
package crowK8S
import (
    "context"
    coreV1 "k8s.io/api/core/v1"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func ApplyServiceByNodePort(clientSet *kubernetes.Clientset,namespaceName string,serviceName string,nodePort int32)(serviceInfo *coreV1.Service,err error)  {
    service,err := clientSet.CoreV1().Services(namespaceName).Get(context.TODO(),serviceName,metaV1.GetOptions{})
    if err !=nil {
        return serviceInfo,err
    }
    service.Spec.Ports[0].NodePort = nodePort
    serviceInfo,err = clientSet.CoreV1().Services(namespaceName).Update(context.TODO(),service,metaV1.UpdateOptions{})
    if err !=nil {
        return serviceInfo,err
    }
    return serviceInfo,nil
}
  • 調(diào)用
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    serviceInfo,err := crowK8S.ApplyServiceByNodePort(clientSet ,"liubei","nginx",30051)
    fmt.Println(serviceInfo)
}

6. Delete Service

語法

  • 語法
func (ServiceInterface) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
  • 語法示例
err = clientSet.CoreV1().Services(namespaceName).Delete(context.TODO(),serviceName,metaV1.DeleteOptions{})

完整示例

  • 創(chuàng)建函數(shù)
package crowK8S
import (
    "context"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func DeleteService(clientSet *kubernetes.Clientset,namespaceName string,serviceName string)(err error)  {
    err = clientSet.CoreV1().Services(namespaceName).Delete(context.TODO(),serviceName,metaV1.DeleteOptions{})
    if err != nil {
        return err
    }
    return nil
}
  • 調(diào)用
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    err = crowK8S.DeleteService(clientSet,"liubei","nginx")
    if err != nil {
        fmt.Println(err)
    }else {
        fmt.Println("刪除成功")
    }
}

結(jié)果打印

刪除成功

以上就是Go語言開發(fā)k8s之Service操作解析的詳細內(nèi)容,更多關(guān)于Go開發(fā)k8s Service操作的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • golang壓縮與解壓縮文件的示例代碼

    golang壓縮與解壓縮文件的示例代碼

    這篇文章主要給大家介紹了golang壓縮與解壓縮文件,文中通過代碼示例給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-02-02
  • Go Struct結(jié)構(gòu)體的具體實現(xiàn)

    Go Struct結(jié)構(gòu)體的具體實現(xiàn)

    Go語言中通過結(jié)構(gòu)體的內(nèi)嵌再配合接口比面向?qū)ο缶哂懈叩臄U展性和靈活性,本文主要介紹了Go Struct結(jié)構(gòu)體的具體實現(xiàn),感興趣的可以了解一下
    2023-03-03
  • Go 基于令牌桶的限流器實現(xiàn)

    Go 基于令牌桶的限流器實現(xiàn)

    如果一般流量過大,下游系統(tǒng)反應(yīng)不過來,這個時候就需要限流了,本文主要介紹了Go 基于令牌桶的限流器實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Go歸并排序算法的實現(xiàn)方法

    Go歸并排序算法的實現(xiàn)方法

    歸并排序采用的也是分治的策略,把原本的問題先分解成一些小問題進行求解,再把這些小問題各自的答案修整到一起得到原本問題的答案,從而達到分而治之的目的,對Go歸并排序算法相關(guān)知識感興趣的朋友一起看看吧
    2022-04-04
  • Go基本數(shù)據(jù)類型與string類型互轉(zhuǎn)

    Go基本數(shù)據(jù)類型與string類型互轉(zhuǎn)

    本文主要介紹了Go基本數(shù)據(jù)類型與string類型互轉(zhuǎn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • go語言中的Stringer的使用示例詳解

    go語言中的Stringer的使用示例詳解

    Go 語言中的 Stringer 是一個非常有用的接口,它在標(biāo)準(zhǔn)庫的 fmt 包中定義,Stringer 接口允許類型定義它們的字符串表示方式,這在格式化輸出時特別有用,這篇文章主要介紹了go語言中的Stringer的使用,需要的朋友可以參考下
    2025-02-02
  • Golang Gin框架實現(xiàn)多種數(shù)據(jù)格式返回結(jié)果詳解

    Golang Gin框架實現(xiàn)多種數(shù)據(jù)格式返回結(jié)果詳解

    這篇文章主要介紹了Golang Gin框架實現(xiàn)多種數(shù)據(jù)格式返回結(jié)果,我們都知道,一個完整的請求包含請求和處理請求以及結(jié)果返回三個步驟,在服務(wù)器端對請求處理完成以后,會將結(jié)果返回給客戶端,在gin框架中,支持返回多種請求數(shù)據(jù)格式,下面我們一起來看看
    2023-05-05
  • go引入自建包名報錯:package?XXX?is?not?in?std解決辦法

    go引入自建包名報錯:package?XXX?is?not?in?std解決辦法

    這篇文章主要給大家介紹了go引入自建包名報錯:package?XXX?is?not?in?std的解決辦法,這是在寫測試引入包名的時候遇到的錯誤提示,文中將解決辦法介紹的非常詳細,需要的朋友可以參考下
    2023-12-12
  • golang實現(xiàn)分頁算法實例代碼

    golang實現(xiàn)分頁算法實例代碼

    這篇文章主要給大家介紹了關(guān)于golang實現(xiàn)分頁算法的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-09-09
  • Golang HTML 模板使用指南示例詳解

    Golang HTML 模板使用指南示例詳解

    本文詳細介紹了Golang HTML模板的使用方法,包括基礎(chǔ)模板、高級模板、完整應(yīng)用示例、CSS樣式、JavaScript交互等,文章強調(diào)了模板組織、代碼復(fù)用、語義化HTML、響應(yīng)式設(shè)計、性能優(yōu)化等最佳實踐,感興趣的朋友跟隨小編一起看看吧
    2025-01-01

最新評論