Go-整合Nacos(小试牛刀)

前言

最近在搞JAVA领域的Nacos,看了Nacos相关源码,趁着深夜,用Go玩玩Nacos,小试牛刀!

获取Nacos整合包

go get github.com/nacos-group/nacos-sdk-go

在这里插入图片描述
git上有现成的例子,写的挺好的,只是跑起来会把注册的节点都又删除,不太人性

Nacos服务端搭建

关于这块我不多说,详情请看我JAVA领域的文章Nacos-深入浅出

Nacos客户端搭建

service_client_example.go

package main

import (
	"fmt"

	"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

func ExampleServiceClient_RegisterServiceInstance(client naming_client.INamingClient, param vo.RegisterInstanceParam) {
	success, _ := client.RegisterInstance(param)
	fmt.Printf("注册服务实例:%+v,result:%+v \n\n", param, success)
}

func ExampleServiceClient_DeRegisterServiceInstance(client naming_client.INamingClient, param vo.DeregisterInstanceParam) {
	success, _ := client.DeregisterInstance(param)
	fmt.Printf("注销服务实例:%+v,result:%+v \n\n", param, success)
}

func ExampleServiceClient_GetService(client naming_client.INamingClient, param vo.GetServiceParam) {
	service, _ := client.GetService(param)
	fmt.Printf("获取服务:%+v, result:%+v \n\n", param, service)
}

func ExampleServiceClient_SelectAllInstances(client naming_client.INamingClient, param vo.SelectAllInstancesParam) {
	instances, _ := client.SelectAllInstances(param)
	fmt.Printf("选择所有实例:%+v, result:%+v \n\n", param, instances)
}

func ExampleServiceClient_SelectInstances(client naming_client.INamingClient, param vo.SelectInstancesParam) {
	instances, _ := client.SelectInstances(param)
	fmt.Printf("选择实例:%+v, result:%+v \n\n", param, instances)
}

func ExampleServiceClient_SelectOneHealthyInstance(client naming_client.INamingClient, param vo.SelectOneHealthInstanceParam) {
	instances, _ := client.SelectOneHealthyInstance(param)
	fmt.Printf("选择实例:%+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("获取所有服务:%+v, result:%+v \n\n", param, service)
}

main.go

package main

import (
	"fmt"
	"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/vo"
)

var client naming_client.INamingClient

/**
 * 初始化Nacos客户端
 */
func intiNacosClient() {

	sc := []constant.ServerConfig{
		{
			IpAddr: "localhost", // Nacos的服务地址
			Port:   8848,        // Nacos的服务端口
		},
	}
	//或 一种更优雅的方式来创建 ServerConfig
	_ = []constant.ServerConfig{
		*constant.NewServerConfig("console.nacos.io", 80),
	}

	cc := constant.ClientConfig{
		NamespaceId:         "",                                   // ACM的命名空间Id 当namespace是public时,此处填空字符串。
		TimeoutMs:           5000,                                 // 请求Nacos服务端的超时时间,默认是10000ms
		NotLoadCacheAtStart: true,                                 // 在启动的时候不读取缓存在CacheDir的service信息
		LogDir:              "/Users/xiaodao/Desktop/nacos/log",   // 日志存储路径
		CacheDir:            "/Users/xiaodao/Desktop/nacos/cache", // 缓存service信息的目录,默认是当前运行目录
		RotateTime:          "1h",                                 // 日志轮转周期,比如:30m, 1h, 24h, 默认是24h
		MaxAge:              3,                                    // 日志最大文件数,默认3
		LogLevel:            "debug",                              // 日志默认级别,值必须是:debug,info,warn,error,默认值是info
	}
	//或 一种更优雅的方式来创建 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"),
	)

	// 一种更优雅的方式来创建命名客户端
	clientTemp, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)

	if err != nil {
		panic(err)
	}

	client = clientTemp

}

/**
 * 输入指令
 */
func enterInstruction() int {
	var x int
	fmt.Println("请输入指令")
	fmt.Scan(&x)
	return x
}

/**
 * 流程判断
 */
func process(instruction int) {

	switch {
		case instruction == 1:
			t1()
		case instruction == 2:
			t2()
		case instruction == 3:
			t3()
		case instruction == 4:
			t4()
		case instruction == 5:
			t5()
		case instruction == 6:
			t6()
		case instruction == 7:
			t7()
		case instruction == 8:
			t8()
		case instruction == 9:
			t9()
		case instruction == 10:
			t10()
		case instruction == 11:
			t11()
		case instruction == 12:
			t12()
		case instruction == 13:
			t13()
		case instruction == 14:
			t14()
		case instruction == 15:
			t15()
	}

}

func main() {

	//初始化Nacos客户端
	intiNacosClient()

	for {
		instruction := enterInstruction()
		fmt.Printf("当前指令==>:%d\n", instruction)
		if instruction == 0 {
			return
		}
		process(instruction)
	}

}

/**
 * 注册默认集群和组
 * ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
 */
func t1() {
	ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
		Ip:          "10.0.0.11",
		Port:        8848,
		ServiceName: "demo.go",
		Weight:      10,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
		Metadata:    map[string]string{"idc": "shanghai"},
	})
}

/**
 * 使用集群名称注册
 * GroupName=DEFAULT_GROUP
 */
func t2() {
	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,
	})
}

/**
 * 注册不同的集群
 * GroupName=DEFAULT_GROUP
 */
func t3() {
	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,
	})
}

/**
 * 注册不同的组
 */
func t4() {
	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,
	})
}

/**
 * 注销 使用 ip,port,serviceName 注销  ClusterName=DEFAULT, GroupName=DEFAULT_GROUP
 * Note:ip=10.0.0.10,port=8848 应该属于集群 DEFAULT and the group of DEFAULT_GROUP.
 */
func t5() {
	ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
		Ip:          "10.0.0.10",
		Port:        8848,
		ServiceName: "demo.go",
		Ephemeral:   true, //it must be true
	})
}

/**
 * 注销 使用 ip,port,serviceName,cluster 注销 GroupName=DEFAULT_GROUP
 * Note:ip=10.0.0.10,port=8848,cluster=cluster-a 应该属于 DEFAULT_GROUP.
 */
func t6() {
	ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
		Ip:          "10.0.0.11",
		Port:        8848,
		ServiceName: "demo.go",
		Cluster:     "cluster-a",
		Ephemeral:   true, //it must be true
	})
}

/**
 * 注销 ip,port,serviceName,cluster,group
 */
func t7() {
	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
	})
}

/**
 * 使用 serviceName 获取服务
 * ClusterName=DEFAULT, GroupName=DEFAULT_GROUP
 */
func t8() {
	ExampleServiceClient_GetService(client, vo.GetServiceParam{
		ServiceName: "demo.go",
	})
}

/**
 * 使用 serviceName 和 cluster 获取服务
 * GroupName=DEFAULT_GROUP
 */
func t9() {
	ExampleServiceClient_GetService(client, vo.GetServiceParam{
		ServiceName: "demo.go",
		Clusters:    []string{"cluster-a", "cluster-b"},
	})
}

/**
 * 获取服务 serviceName
 * ClusterName=DEFAULT
 */
func t10() {
	ExampleServiceClient_GetService(client, vo.GetServiceParam{
		ServiceName: "demo.go",
		GroupName:   "group-a",
	})
}

/**
 * 查询所有服务 返回所有实例 ,包括 healthy=false,enable=false,weight<=0
 * ClusterName=DEFAULT, GroupName=DEFAULT_GROUP
 */
func t11() {
	ExampleServiceClient_SelectAllInstances(client, vo.SelectAllInstancesParam{
		ServiceName: "demo.go",
	})
}

/**
 * 查询所有服务
 * GroupName=DEFAULT_GROUP
 */
func t12() {
	ExampleServiceClient_SelectAllInstances(client, vo.SelectAllInstancesParam{
		ServiceName: "demo.go",
		Clusters:    []string{"cluster-a", "cluster-b"},
	})
}

/**
 * 查询所有服务
 * ClusterName=DEFAULT
 */
func t13() {
	ExampleServiceClient_SelectAllInstances(client, vo.SelectAllInstancesParam{
		ServiceName: "demo.go",
		GroupName:   "group-a",
	})
}

/**
 * 查询说有实例 只返回的实例 healthy=${HealthyOnly},enable=true and weight>0
 * ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
 */
func t14() {
	ExampleServiceClient_SelectInstances(client, vo.SelectInstancesParam{
		ServiceName: "demo.go",
	})
}

/**
 * 选择一个健康的实例 通过 WRR 策略返回一个实例进行负载均衡
 * 并且实例应该是 health=true,enable=true and weight>0
 * ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
 */
func t15() {
	ExampleServiceClient_SelectOneHealthyInstance(client, vo.SelectOneHealthInstanceParam{
		ServiceName: "demo.go",
	})
}

这里其实就是搬运一下GitHub上的例子,然后根据键盘输入,执行对应的逻辑!让代码逻辑更加直观
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员劝退师-TAO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值