入门案例
案例1
使用 rpcx 默认的数据序列化方案:golang 原生 struct + msgpack。
service
定义一个简单的服务和数据结构,用于演示如何使用 Go 语言中的 rpcx 框架实现远程过程调用(RPC)。
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
|
// Package example defines data structure and services.
package example
type Args struct {
A int
B int
}
type Reply struct {
C int
}
type Arith int
func (t *Arith) Mul(ctx context.Context, args *Args, reply *Reply) error {
reply.C = args.A * args.B
fmt.Printf("call: %d * %d = %d\n", args.A, args.B, reply.C)
return nil
}
func (t *Arith) Add(ctx context.Context, args *Args, reply *Reply) error {
reply.C = args.A + args.B
fmt.Printf("call: %d + %d = %d\n", args.A, args.B, reply.C)
return nil
}
func (t *Arith) Say(ctx context.Context, args *string, reply *string) error {
*reply = "hello " + *args
return nil
}
type Greeter struct{}
func (s *Greeter) Say(ctx context.Context, name *string, reply *string) error {
*reply = fmt.Sprintf("hello %s!", *name)
return nil
}
|
以上代码展示了如何通过 rpcx 框架实现了一个简单的 RPC 服务: