08.grpc注册nacos
# 01.golang gRPC注册nacos
# 1.0 目录结构
# 1.1 pb/person.proto
syntax = "proto3";
option go_package = "./person";
package pb;
message Person {
string name = 1;
int32 age = 2;
}
// 添加 rpc服务
service hello {
rpc sayHello (Person) returns (Person);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 1.2 nacos-server8800/nacos_server.go
package main
import (
"awesomeProject/pb/person"
"context"
"fmt"
"net"
"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"
"google.golang.org/grpc"
)
// 定义类
type Children struct {
}
// 绑定类方法, 实现借口
func (this *Children) SayHello(ctx context.Context, p *person.Person) (*person.Person, error) {
p.Name = "hello " + p.Name
return p, nil
}
func main() {
RegisterNacos()
//////////////////////以下为 grpc 服务远程调用//////////////////////////////
// 1.初始化 grpc 对象,
grpcServer := grpc.NewServer()
// 2.注册服务
person.RegisterHelloServer(grpcServer, new(Children))
// 3.设置监听, 指定 IP/port
listener, err := net.Listen("tcp", "127.0.0.1:8800")
if err != nil {
fmt.Println("Listen err:", err)
return
}
defer listener.Close()
fmt.Println("服务启动... ")
// 4. 启动服务
grpcServer.Serve(listener)
}
func RegisterNacos() {
// 创建clientConfig
clientConfig := constant.ClientConfig{
//NamespaceId: "e525eafa-f7d7-4029-83d9-008937f9d468", // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时,此处填空字符串。
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: "/tmp/nacos/log",
CacheDir: "/tmp/nacos/cache",
RotateTime: "1h",
MaxAge: 3,
LogLevel: "debug",
}
// 至少一个ServerConfig
serverConfigs := []constant.ServerConfig{
{
IpAddr: "127.0.0.1",
ContextPath: "/nacos",
Port: 8848,
Scheme: "http",
},
}
// 创建服务发现客户端 (推荐)
namingClient, err := clients.NewNamingClient(
vo.NacosClientParam{
ClientConfig: &clientConfig,
ServerConfigs: serverConfigs,
},
)
if err != nil {
fmt.Println("clients.NewNamingClient err,", err)
}
success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{
Ip: "127.0.0.1",
Port: 8800,
ServiceName: "demo.go",
Weight: 10,
Enable: true,
Healthy: true,
Ephemeral: true,
Metadata: map[string]string{"idc": "shanghai"},
ClusterName: "cluster-a", // 默认值DEFAULT
GroupName: "group-a", // 默认值DEFAULT_GROUP
})
if !success {
return
} else {
fmt.Println("namingClient.RegisterInstance Success")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# 1.3 nacos-client/nacos_client.go
package main
import (
"awesomeProject/pb/person"
"context"
"fmt"
"strconv"
"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"
"google.golang.org/grpc"
)
func main() {
// 创建clientConfig
clientConfig := constant.ClientConfig{
//NamespaceId: "e525eafa-f7d7-4029-83d9-008937f9d468", // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时,此处填空字符串。
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: "/tmp/nacos/log",
CacheDir: "/tmp/nacos/cache",
RotateTime: "1h",
MaxAge: 3,
LogLevel: "debug",
}
// 至少一个ServerConfig
serverConfigs := []constant.ServerConfig{
{
IpAddr: "127.0.0.1",
ContextPath: "/nacos",
Port: 8848,
Scheme: "http",
},
}
// 创建服务发现客户端的另一种方式 (推荐)
namingClient, err := clients.NewNamingClient(
vo.NacosClientParam{
ClientConfig: &clientConfig,
ServerConfigs: serverConfigs,
},
)
// SelectAllInstance可以返回全部实例列表,包括healthy=false,enable=false,weight<=0
instances, err := namingClient.SelectAllInstances(vo.SelectAllInstancesParam{
ServiceName: "demo.go",
GroupName: "group-a", // 默认值DEFAULT_GROUP
Clusters: []string{"cluster-a"}, // 默认值DEFAULT
})
fmt.Println(instances)
// SelectOneHealthyInstance将会按加权随机轮询的负载均衡策略返回一个健康的实例
// 实例必须满足的条件:health=true,enable=true and weight>0
instance, err := namingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
ServiceName: "demo.go",
GroupName: "group-a", // 默认值DEFAULT_GROUP
Clusters: []string{"cluster-a"}, // 默认值DEFAULT
})
addr := instance.Ip + ":" + strconv.Itoa(int(instance.Port))
fmt.Println(addr)
//////////////////////以下为 grpc 服务远程调用//////////////////////////////
// 1. 链接服务
//grpcConn, _ := grpc.Dial("127.0.0.1:8800", grpc.WithInsecure())
// 使用 服务发现consul 上的 IP/port 来与服务建立链接
grpcConn, _ := grpc.Dial(addr, grpc.WithInsecure())
// 2. 初始化 grpc 客户端
grpcClient := person.NewHelloClient(grpcConn)
var person person.Person
person.Name = "Andy"
person.Age = 18
// 3. 调用远程函数
p, err := grpcClient.SayHello(context.TODO(), &person)
fmt.Println(p, err)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# 1.4 nacos-server8801/nacos_server.go
package main
import (
"awesomeProject/pb/person"
"context"
"fmt"
"net"
"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"
"google.golang.org/grpc"
)
// 定义类
type Children struct {
}
// 绑定类方法, 实现借口
func (this *Children) SayHello(ctx context.Context, p *person.Person) (*person.Person, error) {
p.Name = "hello " + p.Name
return p, nil
}
func main() {
RegisterNacos()
//////////////////////以下为 grpc 服务远程调用//////////////////////////////
// 1.初始化 grpc 对象,
grpcServer := grpc.NewServer()
// 2.注册服务
person.RegisterHelloServer(grpcServer, new(Children))
// 3.设置监听, 指定 IP/port
listener, err := net.Listen("tcp", "127.0.0.1:8801")
if err != nil {
fmt.Println("Listen err:", err)
return
}
defer listener.Close()
fmt.Println("服务启动... ")
// 4. 启动服务
grpcServer.Serve(listener)
}
func RegisterNacos() {
// 创建clientConfig
clientConfig := constant.ClientConfig{
//NamespaceId: "e525eafa-f7d7-4029-83d9-008937f9d468", // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时,此处填空字符串。
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: "/tmp/nacos/log",
CacheDir: "/tmp/nacos/cache",
RotateTime: "1h",
MaxAge: 3,
LogLevel: "debug",
}
// 至少一个ServerConfig
serverConfigs := []constant.ServerConfig{
{
IpAddr: "127.0.0.1",
ContextPath: "/nacos",
Port: 8848,
Scheme: "http",
},
}
// 创建服务发现客户端 (推荐)
namingClient, err := clients.NewNamingClient(
vo.NacosClientParam{
ClientConfig: &clientConfig,
ServerConfigs: serverConfigs,
},
)
if err != nil {
fmt.Println("clients.NewNamingClient err,", err)
}
success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{
Ip: "127.0.0.1",
Port: 8801,
ServiceName: "demo.go",
Weight: 10,
Enable: true,
Healthy: true,
Ephemeral: true,
Metadata: map[string]string{"idc": "shanghai"},
ClusterName: "cluster-a", // 默认值DEFAULT
GroupName: "group-a", // 默认值DEFAULT_GROUP
})
if !success {
return
} else {
fmt.Println("namingClient.RegisterInstance Success")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# 1.5 运行服务端测试
- 运行命令安装包
go mod tidy
1
- 生成protobuf文件
cd pb
protoc --go_out=plugins=grpc:./ *.proto
1
2
2
保证nacos服务正常运行:
http://127.0.0.1:8848/nacos- 运行服务端
// 启动 server8000
xiaonaiqiang1@ZBMac-C02CW08SM nacos-grpc-gotest % cd nacos-server8800
xiaonaiqiang1@ZBMac-C02CW08SM nacos-server8800 % go run nacos_server.go
// 启动server8801
xiaonaiqiang1@ZBMac-C02CW08SM nacos-grpc-gotest % cd nacos-server8801
xiaonaiqiang1@ZBMac-C02CW08SM nacos-server8801 % go run nacos_server.go
1
2
3
4
5
6
2
3
4
5
6
启动客户端测试负载均衡
xiaonaiqiang1@ZBMac-C02CW08SM nacos-grpc-gotest % cd nacos-client
// 运行第一次访问的是 127.0.0.1:8800
xiaonaiqiang1@ZBMac-C02CW08SM nacos-client % go run nacos_client.go
127.0.0.1:8800
// 运行第一次访问的是 127.0.0.1:8801
xiaonaiqiang1@ZBMac-C02CW08SM nacos-client % go run nacos_client.go
127.0.0.1:8801
1
2
3
4
5
6
7
2
3
4
5
6
7
- 查看nacos服务注册的状态
# 02.接入nacos配置中心
# 2.1 管理nacos
# 1、新建“命名空间”
# 2、添加配置
添加配置文件
# 2.2 配置中心使用
package main
import (
"fmt"
"github.com/BurntSushi/toml"
"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"
"time"
)
type User struct {
Name string `toml:"name" json:"name"`
}
func main() {
sc := []constant.ServerConfig{{
IpAddr: "127.0.0.1",
Port: 8848,
}}
cc := constant.ClientConfig{
// 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId,当namespace是public时,此处填空字符串。
NamespaceId: "743b45f1-b34d-4dfa-8ae8-2304682945a4",
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: "log",
CacheDir: "cache",
LogLevel: "debug",
}
configClient, err := clients.CreateConfigClient(map[string]interface{}{
"serverConfigs": sc,
"clientConfig": cc,
})
if err != nil {
panic(err)
}
// 配置拉取
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: "user-web.toml",
Group: "dev",
})
if err != nil {
panic(err)
}
fmt.Println("第一次启动读取----->", content) //字符串 - yaml
u := User{}
_, err = toml.Decode(content, &u)
if err != nil {
fmt.Println(err)
}
fmt.Println("第一次读取name为---->", u.Name)
// 配置监听
err = configClient.ListenConfig(vo.ConfigParam{
DataId: "user-web.toml",
Group: "dev",
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("配置文件发生了变化...")
fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
_, err = toml.Decode(data, &u)
fmt.Println("文件修改后结果---->", u.Name)
},
})
time.Sleep(300 * time.Second)
}
/*
第一次启动读取-----> name = "root"
文件修改后结果----> root
配置文件发生了变化...
group:dev, dataId:user-web.toml, data:name = "root1"
文件修改后结果----> root1
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
编辑 (opens new window)
上次更新: 2024/3/13 15:35:10