最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

1. 結構體

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結構體如下:

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"`
}

其中TypeMetaObjectMeta ServiceSpec ServiceStatus結構體如下:

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"`
}

對應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"`
}

對應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"`
}

對應原生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 信息,大家可以對照理解一下以上結構體

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)
}
  • 結果輸出

本來是一個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)
}

結果顯示

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

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("刪除成功")
    }
}

結果打印

刪除成功

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

相關文章

  • Go語言變量與類型使用簡明指南

    Go語言變量與類型使用簡明指南

    Go語言是靜態(tài)編程語言,在Go語言中數(shù)據(jù)類型用于聲明函數(shù)和變量,這篇文章主要介紹了Go語言變量與類型使用的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2025-09-09
  • golang實現(xiàn)大文件讀取的代碼示例

    golang實現(xiàn)大文件讀取的代碼示例

    在實際工作,我們需要讀取大數(shù)據(jù)文件,文件可能上G百G,所以我們不可能一次性的讀取到內(nèi)存,接下來本文給大家介紹了golang實現(xiàn)大文件讀取的示例,需要的朋友可以參考下
    2024-04-04
  • Go語言中slice的用法實例分析

    Go語言中slice的用法實例分析

    這篇文章主要介紹了Go語言中slice的用法,實例分析了slice的功能及使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-02-02
  • Go語言Handler詳細說明

    Go語言Handler詳細說明

    這篇文章主要介紹了Go語言Handler詳細說明,Handler用于處理請求并給予響應。更嚴格地說,用來讀取請求體、并將請求對應的響應字段(respones header)寫入ResponseWriter中,需要的朋友可以參考下
    2022-04-04
  • golang實現(xiàn)簡單rpc調(diào)用過程解析

    golang實現(xiàn)簡單rpc調(diào)用過程解析

    這篇文章主要介紹了golang實現(xiàn)簡單rpc調(diào)用,包括RPC具體實現(xiàn)結合實例代碼給大家講解的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • 淺談golang for 循環(huán)中使用協(xié)程的問題

    淺談golang for 循環(huán)中使用協(xié)程的問題

    這篇文章主要介紹了淺談golang for 循環(huán)中使用協(xié)程的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • 使用Go語言中的Context取消協(xié)程執(zhí)行的操作代碼

    使用Go語言中的Context取消協(xié)程執(zhí)行的操作代碼

    在 Go 語言中,協(xié)程(goroutine)是一種輕量級的線程,非常適合處理并發(fā)任務,然而,如何優(yōu)雅地取消正在運行的協(xié)程是一個常見的問題,本文將通過一個具體的例子來展示如何使用 context 包來取消協(xié)程的執(zhí)行,需要的朋友可以參考下
    2024-11-11
  • Go channel發(fā)送方和接收方如何相互阻塞等待源碼解讀

    Go channel發(fā)送方和接收方如何相互阻塞等待源碼解讀

    這篇文章主要為大家介紹了Go channel發(fā)送方和接收方如何相互阻塞等待源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-12-12
  • Go語言中掃描Redis中大量key的示例代碼

    Go語言中掃描Redis中大量key的示例代碼

    在 Redis 中,當我們需要遍歷大量的鍵時,直接使用 KEYS 命令會面臨性能瓶頸,尤其是在鍵數(shù)量非常多的情況下,今天,我們將通過兩個示例代碼,詳細講解如何在 Go 語言中使用 SCAN 命令遍歷 Redis 鍵,需要的朋友可以參考下
    2024-08-08
  • 一文告訴你大神是如何學習Go語言之make和new

    一文告訴你大神是如何學習Go語言之make和new

    當我們想要在 Go 語言中初始化一個結構時,其實會使用到兩個完全不同的關鍵字,也就是 make 和 new,同時出現(xiàn)兩個用于『初始化』的關鍵字對于初學者來說可能會感到非常困惑,不過它們兩者有著卻完全不同的作用,本文就和大家詳細講講
    2023-02-02

最新評論

漳州市| 会同县| 德化县| 彭泽县| 镇平县| 阿合奇县| 八宿县| 安阳县| 稻城县| 阿巴嘎旗| 武安市| 洛宁县| 金阳县| 新民市| 宜州市| 威远县| 玛沁县| 巴马| 平邑县| 什邡市| 连州市| 渑池县| 高密市| 卢龙县| 桑日县| 澄迈县| 萍乡市| 承德市| 彭水| 汝南县| 馆陶县| 紫金县| 滕州市| 扶沟县| 太原市| 华阴市| 婺源县| 平陆县| 广水市| 周至县| 双辽市|