go集成nacos

1,go集成nacos 注册实例与注销实例

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"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)

var client naming_client.INamingClient

/*
*
注册实例
*/
func Init(ip string, port uint64, serviceName string, logDir string, cacheDir string, namespaceId string, ipLocal string) {
	sc := []constant.ServerConfig{
		{
			IpAddr: ip,
			Port:   8848,
		},
	}

	cc := constant.ClientConfig{
		NamespaceId:         namespaceId, // 如果有命名空间,填上对应的命名空间ID
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              logDir,
		CacheDir:            cacheDir,
		LogLevel:            "error",
	}

	var err error
	client, err = clients.CreateNamingClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})

	if err != nil {
		fmt.Println(err)
	}
	// 注册实例
	instance := &vo.RegisterInstanceParam{
		Ip:          ipLocal,
		Port:        port,
		ServiceName: serviceName,
		Weight:      10,
		ClusterName: "DEFAULT",
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
		Metadata:    map[string]string{"version": "1.0"},
	}
	success, err := client.RegisterInstance(*instance)
	if err != nil {
		fmt.Println("Nacos 注册实例失败 err=", err)
		return
	}
	if success {
		fmt.Println("Nacos 注册实例成功")
	}

	instances, err := client.SelectInstances(vo.SelectInstancesParam{
		ServiceName: "hall",
		GroupName:   "DEFAULT_GROUP",
		HealthyOnly: true, //HealthyOnly参数是一个可选参数,如果设置为true,则表示只返回健康的服务实例
	})
	if err != nil {
		fmt.Println("查询指定服务的实例信息 err=", err)
	}

	for _, instance := range instances {
		fmt.Println(instance.ServiceName + " " + instance.Ip + ":" + fmt.Sprint(instance.Port))
	}

	// 模拟服务运行
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Println(w, "Hello, this is my Go service!")
	})
	fmt.Println("服务启动成功 port=", port)
	err = http.ListenAndServe(":"+strconv.FormatUint(port, 10), nil)
	if err != nil {
		return
	}
}

/*
*
注销实例
*/
func DeregisterInstance(port uint64, serviceName string, ip string) {
	// 注销实例
	instance := &vo.DeregisterInstanceParam{
		Ip:          ip,
		Port:        port,
		ServiceName: serviceName,
		Cluster:     "DEFAULT",
		GroupName:   "DEFAULT_GROUP",
		Ephemeral:   true,
	}
	success, err := client.DeregisterInstance(*instance)
	if err != nil {
		fmt.Println("Nacos 注销实例失败 err=", err)
	}
	if success {
		fmt.Println("Nacos 注销实例成功")
	}
}

func Exit(port uint64, serviceName string, ip string) {
	// 创建一个通道来接收信号
	sigCh := make(chan os.Signal, 1)
	// 监听指定的信号
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

	// 启动一个 goroutine 来处理接收到的信号
	go func() {
		// 等待信号
		sig := <-sigCh
		fmt.Println("接收到信号:", sig)

		// 在这里执行程序关闭前的清理操作
		// 在这里编写你的程序逻辑
		fmt.Println("开始关闭程序")
		DeregisterInstance(port, serviceName, ip)
		fmt.Println("关闭程序-end all")
		// 退出程序
		os.Exit(0)
	}()
}

func GetIp(local bool) string {
	var ip = ""
	if local {
		ip = nip()
	} else {
		ip = wip()
	}
	fmt.Println("GetIp=" + ip)
	return ip
}

/*
*
获取内网ip
*/
func nip() string {
	ifaces, err := net.Interfaces()
	if err != nil {
		fmt.Println(err)
		return ""
	}

	for _, iface := range ifaces {
		addrs, err := iface.Addrs()
		if err != nil {
			fmt.Println(err)
			continue
		}
		for _, addr := range addrs {
			ipnet, ok := addr.(*net.IPNet)
			if ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
				ip := ipnet.IP
				fmt.Println(ip.String())
				return ip.String()
			}
		}
	}
	return ""
}

/*
*
获取外网ip
*/
func wip() string {
	resp, err := http.Get("https://api.ipify.org?format=text")
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer resp.Body.Close()

	ip, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return ""
	}

	fmt.Println(string(ip))
	return string(ip)
}

func main() {

	ip := "127.0.0.1"
	var port uint64 = 8080
	serviceName := "gs-serviceTest"
	logDir := "/data/giftpanel/nacosLogs"
	cacheDir := "/data/giftpanel/nacosCache"
	namespaceId := "gs-test"
	//GetIp(false)
	localIp := GetIp(true)
	Exit(port, serviceName, localIp)
	Init(ip, port, serviceName, logDir, cacheDir, namespaceId, localIp)
}

你可能感兴趣的:(GoLang,Nacos,golang,开发语言,后端,nacos)