Created
October 28, 2024 13:45
-
-
Save fjrti/4fe6cfd60dc925352474a389ac0b0533 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 注册: | |
package main | |
import ( | |
"github.com/nacos-group/nacos-sdk-go/v2/clients" | |
"github.com/nacos-group/nacos-sdk-go/v2/common/constant" | |
"github.com/nacos-group/nacos-sdk-go/v2/vo" | |
"fmt" | |
) | |
func main() { | |
// 创建服务器配置 | |
serverConfigs := []constant.ServerConfig{ | |
*constant.NewServerConfig("127.0.0.1", 8848, constant.WithScheme("http")), | |
} | |
// 创建客户端配置 | |
clientConfig := *constant.NewClientConfig( | |
constant.WithNamespaceId("public"), // 如果使用默认命名空间,填空字符串 | |
constant.WithTimeoutMs(5000), | |
constant.WithNotLoadCacheAtStart(true), | |
constant.WithLogDir("/tmp/nacos/log"), | |
constant.WithCacheDir("/tmp/nacos/cache"), | |
constant.WithLogLevel("debug"), | |
) | |
// 创建命名客户端 | |
namingClient, err := clients.NewNamingClient( | |
vo.NacosClientParam{ | |
ClientConfig: &clientConfig, | |
ServerConfigs: serverConfigs, | |
}, | |
) | |
if err != nil { | |
fmt.Printf("创建命名客户端失败: %v\n", err) | |
return | |
} | |
// 注册服务实例 | |
success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{ | |
Ip: "192.168.1.100", | |
Port: 8080, | |
ServiceName: "demo-service", | |
Weight: 10, | |
Enable: true, | |
Healthy: true, | |
Ephemeral: true, | |
}) | |
if !success || err != nil { | |
fmt.Printf("注册服务实例失败: %v\n", err) | |
return | |
} | |
fmt.Println("服务实例注册成功") | |
} | |
// 访问 | |
// 发现服务实例 | |
instances, err := namingClient.SelectInstances(vo.SelectInstancesParam{ | |
ServiceName: "demo-service", | |
HealthyOnly: true, | |
}) | |
if err != nil { | |
fmt.Printf("发现服务实例失败: %v\n", err) | |
return | |
} | |
for _, instance := range instances { | |
fmt.Printf("发现服务实例: IP=%s, Port=%d\n", instance.Ip, instance.Port) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment