代码如下:
package main
import (
"fmt"
"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/vo"
"strconv"
"sync"
)
func main() {
// 创建 Nacos 服务器的配置 http://10.10.101.25:30310/
serverConfigs := []constant.ServerConfig{
*constant.NewServerConfig("10.10.101.25", 30310),
}
// 创建客户端配置,包括用户名和密码
clientConfig := *constant.NewClientConfig(
constant.WithNamespaceId(""), // 如果有namespace,可以在此设置
constant.WithTimeoutMs(5000),
constant.WithNotLoadCacheAtStart(true),
constant.WithLogDir("/Users/liyinlong/myimg/youchu/temp/nacos/log"),
constant.WithCacheDir("/Users/liyinlong/myimg/youchu/temp/nacos/cache"),
constant.WithUsername("nacos"), // Nacos 用户名
constant.WithPassword("nacos"), // Nacos 密码
)
// 创建 Nacos Naming 客户端
namingClient, err := clients.NewNamingClient(
vo.NacosClientParam{
ClientConfig: &clientConfig,
ServerConfigs: serverConfigs,
},
)
if err != nil {
fmt.Printf("Failed to create Nacos naming client: %v\n", err)
return
}
group := sync.WaitGroup{}
group.Add(10)
for j := 0; j < 30; j++ {
go func() {
for i := 0; i < 50000; i++ {
// 注册服务到 Nacos
success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{
Ip: "192.168.1.100", // 实例的IP
Port: 8080, // 实例的端口
ServiceName: "example-service" + strconv.Itoa(j+i), // 服务名称
Weight: 1.0, // 权重
Enable: true,
Healthy: true,
Ephemeral: false, // 是否是临时实例
Metadata: map[string]string{
"env": "dev", // 自定义元数据
"meta_app_namespace": "example-service" + strconv.Itoa(i),
"meta_app_service_account": "example-service" + strconv.Itoa(i),
"meta_app_version": "1.0.0",
"interface": "com.lyl.useService",
},
})
if err != nil {
fmt.Printf("Failed to register service: %v\n", err)
return
}
if success {
fmt.Println("Service registered successfully!")
} else {
fmt.Println("Service registration failed!")
}
}
fmt.Println("finish register service")
group.Done()
}()
}
group.Wait()
}