• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

go nacos服务发现

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本来想研究一下nacos的服务发现,原来sample这么详细啊,直接运行代码吧:

package main
 
import (
    "fmt"
    "time"
 
    "github.com/nacos-group/nacos-sdk-go/clients"
    "github.com/nacos-group/nacos-sdk-go/clients/naming_client"
    "github.com/nacos-group/nacos-sdk-go/common/constant"
    "github.com/nacos-group/nacos-sdk-go/model"
    "github.com/nacos-group/nacos-sdk-go/util"
    "github.com/nacos-group/nacos-sdk-go/vo"
)
 
func main() {
    sc := []constant.ServerConfig{
        {
            IpAddr: "192.168.100.30",
            Port:   8848,
        },
    }
    //or a more graceful way to create ServerConfig
    _ = []constant.ServerConfig{
        *constant.NewServerConfig("192.168.100.30", 8848),
    }
 
    cc := constant.ClientConfig{
        NamespaceId:         "e525eafa-f7d7-4029-83d9-008937f9d468", //namespace id
        TimeoutMs:           5000,
        NotLoadCacheAtStart: true,
        //LogDir:              "/tmp/nacos/log",
        //    CacheDir:            "/tmp/nacos/cache",
        RotateTime: "1h",
        MaxAge:     3,
        LogLevel:   "debug",
    }
    //or a more graceful way to create ClientConfig
    _ = *constant.NewClientConfig(
        constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"),
        constant.WithTimeoutMs(5000),
        constant.WithNotLoadCacheAtStart(true),
        //constant.WithLogDir("/tmp/nacos/log"),
        //constant.WithCacheDir("/tmp/nacos/cache"),
        constant.WithRotateTime("1h"),
        constant.WithMaxAge(3),
        constant.WithLogLevel("debug"),
    )
 
    // a more graceful way to create naming client
    client, err := clients.NewNamingClient(
        vo.NacosClientParam{
            ClientConfig:  &cc,
            ServerConfigs: sc,
        },
    )
 
    if err != nil {
        panic(err)
    }
 
    //Register with default cluster and group
    //ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
    ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
        Ip:          "10.0.0.10",
        Port:        8848,
        ServiceName: "demo.go",
        Weight:      10,
        Enable:      true,
        Healthy:     true,
        Ephemeral:   true,
        Metadata:    map[string]string{"idc": "shanghai"},
    })
 
    //Register with cluster name
    //GroupName=DEFAULT_GROUP
    ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
        Ip:          "10.0.0.11",
        Port:        8848,
        ServiceName: "demo.go",
        Weight:      10,
        ClusterName: "cluster-a",
        Enable:      true,
        Healthy:     true,
        Ephemeral:   true,
    })
 
    //Register different cluster
    //GroupName=DEFAULT_GROUP
    ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
        Ip:          "10.0.0.12",
        Port:        8848,
        ServiceName: "demo.go",
        Weight:      10,
        ClusterName: "cluster-b",
        Enable:      true,
        Healthy:     true,
        Ephemeral:   true,
    })
 
    //Register different group
    ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
        Ip:          "10.0.0.13",
        Port:        8848,
        ServiceName: "demo.go",
        Weight:      10,
        ClusterName: "cluster-b",
        GroupName:   "group-a",
        Enable:      true,
        Healthy:     true,
        Ephemeral:   true,
    })
    ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
        Ip:          "10.0.0.14",
        Port:        8848,
        ServiceName: "demo.go",
        Weight:      10,
        ClusterName: "cluster-b",
        GroupName:   "group-b",
        Enable:      true,
        Healthy:     true,
        Ephemeral:   true,
    })
 
    //DeRegister with ip,port,serviceName
    //ClusterName=DEFAULT, GroupName=DEFAULT_GROUP
    //Note:ip=10.0.0.10,port=8848 should belong to the cluster of DEFAULT and the group of DEFAULT_GROUP.
    ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
        Ip:          "10.0.0.10",
        Port:        8848,
        ServiceName: "demo.go",
        Ephemeral:   true, //it must be true
    })
 
    //DeRegister with ip,port,serviceName,cluster
    //GroupName=DEFAULT_GROUP
    //Note:ip=10.0.0.10,port=8848,cluster=cluster-a should belong to the group of DEFAULT_GROUP.
    ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
        Ip:          "10.0.0.11",
        Port:        8848,
        ServiceName: "demo.go",
        Cluster:     "cluster-a",
        Ephemeral:   true, //it must be true
    })
 
    //DeRegister with ip,port,serviceName,cluster,group
    ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
        Ip:          "10.0.0.14",
        Port:        8848,
        ServiceName: "demo.go",
        Cluster:     "cluster-b",
        GroupName:   "group-b",
        Ephemeral:   true, //it must be true
    })
 
    //Get service with serviceName
    //ClusterName=DEFAULT, GroupName=DEFAULT_GROUP
    ExampleServiceClient_GetService(client, vo.GetServiceParam{
        ServiceName: "demo.go",
    })
    //Get service with serviceName and cluster
    //GroupName=DEFAULT_GROUP
    ExampleServiceClient_GetService(client, vo.GetServiceParam{
        ServiceName: "demo.go",
        Clusters:    []string{"cluster-a", "cluster-b"},
    })
    //Get service with serviceName ,group
    //ClusterName=DEFAULT
    ExampleServiceClient_GetService(client, vo.GetServiceParam{
        ServiceName: "demo.go",
        GroupName:   "group-a",
    })
 
    //SelectAllInstance return all instances,include healthy=false,enable=false,weight<=0
    //ClusterName=DEFAULT, GroupName=DEFAULT_GROUP
    ExampleServiceClient_SelectAllInstances(client, vo.SelectAllInstancesParam{
        ServiceName: "demo.go",
    })
 
    //SelectAllInstance
    //GroupName=DEFAULT_GROUP
    ExampleServiceClient_SelectAllInstances(client, vo.SelectAllInstancesParam{
        ServiceName: "demo.go",
        Clusters:    []string{"cluster-a", "cluster-b"},
    })
 
    //SelectAllInstance
    //ClusterName=DEFAULT
    ExampleServiceClient_SelectAllInstances(client, vo.SelectAllInstancesParam{
        ServiceName: "demo.go",
        GroupName:   "group-a",
    })
 
    //SelectInstances only return the instances of healthy=${HealthyOnly},enable=true and weight>0
    //ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
    ExampleServiceClient_SelectInstances(client, vo.SelectInstancesParam{
        ServiceName: "demo.go",
    })
 
    //SelectOneHealthyInstance return one instance by WRR strategy for load balance
    //And the instance should be health=true,enable=true and weight>0
    //ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
    ExampleServiceClient_SelectOneHealthyInstance(client, vo.SelectOneHealthInstanceParam{
        ServiceName: "demo.go",
    })
 
    //Subscribe key=serviceName+groupName+cluster
    //Note:We call add multiple SubscribeCallback with the same key.
    param := &vo.SubscribeParam{
        ServiceName: "demo.go",
        Clusters:    []string{"cluster-b"},
        SubscribeCallback: func(services []model.SubscribeService, err error) {
            fmt.Printf("callback111 return services:%s \n\n", util.ToJsonString(services))
        },
    }
    ExampleServiceClient_Subscribe(client, param)
    param2 := &vo.SubscribeParam{
        ServiceName: "demo.go",
        Clusters:    []string{"cluster-b"},
        SubscribeCallback: func(services []model.SubscribeService, err error) {
            fmt.Printf("callback222 return services:%s \n\n", util.ToJsonString(services))
        },
    }
    ExampleServiceClient_Subscribe(client, param2)
    ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
        Ip:          "10.0.0.112",
        Port:        8848,
        ServiceName: "demo.go",
        Weight:      10,
        ClusterName: "cluster-b",
        Enable:      true,
        Healthy:     true,
        Ephemeral:   true,
    })
    //wait for client pull change from server
    time.Sleep(10 * time.Second)
 
    //Now we just unsubscribe callback1, and callback2 will still receive change event
    ExampleServiceClient_UnSubscribe(client, param)
    ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
        Ip:          "10.0.0.112",
        Ephemeral:   true,
        Port:        8848,
        ServiceName: "demo.go",
        Cluster:     "cluster-b",
    })
    //wait for client pull change from server
    time.Sleep(10 * time.Second)
 
    //GeAllService will get the list of service name
    //NameSpace default value is public.If the client set the namespaceId, NameSpace will use it.
    //GroupName default value is DEFAULT_GROUP
    ExampleServiceClient_GetAllService(client, vo.GetAllServiceInfoParam{
        PageNo:   1,
        PageSize: 10,
    })
 
    ExampleServiceClient_GetAllService(client, vo.GetAllServiceInfoParam{
        NameSpace: "0e83cc81-9d8c-4bb8-a28a-ff703187543f",
        PageNo:    1,
        PageSize:  10,
    })
}
 
/*--------------------------------------------------------------------------*/
func ExampleServiceClient_RegisterServiceInstance(client naming_client.INamingClient, param vo.RegisterInstanceParam) {
    success, _ := client.RegisterInstance(param)
    fmt.Printf("RegisterServiceInstance,param:%+v,result:%+v \n\n", param, success)
}
 
func ExampleServiceClient_DeRegisterServiceInstance(client naming_client.INamingClient, param vo.DeregisterInstanceParam) {
    success, _ := client.DeregisterInstance(param)
    fmt.Printf("DeRegisterServiceInstance,param:%+v,result:%+v \n\n", param, success)
}
 
func ExampleServiceClient_GetService(client naming_client.INamingClient, param vo.GetServiceParam) {
    service, _ := client.GetService(param)
    fmt.Printf("GetService,param:%+v, result:%+v \n\n", param, service)
}
 
func ExampleServiceClient_SelectAllInstances(client naming_client.INamingClient, param vo.SelectAllInstancesParam) {
    instances, _ := client.SelectAllInstances(param)
    fmt.Printf("SelectAllInstance,param:%+v, result:%+v \n\n", param, instances)
}
 
func ExampleServiceClient_SelectInstances(client naming_client.INamingClient, param vo.SelectInstancesParam) {
    instances, _ := client.SelectInstances(param)
    fmt.Printf("SelectInstances,param:%+v, result:%+v \n\n", param, instances)
}
 
func ExampleServiceClient_SelectOneHealthyInstance(client naming_client.INamingClient, param vo.SelectOneHealthInstanceParam) {
    instances, _ := client.SelectOneHealthyInstance(param)
    fmt.Printf("SelectInstances,param:%+v, result:%+v \n\n", param, instances)
}
 
func ExampleServiceClient_Subscribe(client naming_client.INamingClient, param *vo.SubscribeParam) {
    client.Subscribe(param)
}
 
func ExampleServiceClient_UnSubscribe(client naming_client.INamingClient, param *vo.SubscribeParam) {
    client.Unsubscribe(param)
}
 
func ExampleServiceClient_GetAllService(client naming_client.INamingClient, param vo.GetAllServiceInfoParam) {
    service, _ := client.GetAllServicesInfo(param)
    fmt.Printf("GetAllService,param:%+v, result:%+v \n\n", param, service)
}

运行结果:

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go类型系统概述发布时间:2022-07-10
下一篇:
2.1Go语言特性发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap