Golang实现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
package main

import (
"fmt"
"myphp.org/demorpc/common"
"net/rpc"
)

func main() {
var args = common.Args{A: 32, B: 14}
var result = common.Result{}

var client, err = rpc.DialHTTP("tcp", "127.0.0.1:9090")
if err != nil {
fmt.Printf("connect rpc server failed, err:%v", err)
}

err = client.Call("MathService.Divide", args, &result)
if err != nil {
fmt.Printf("call math service failed, err:%v", err)
}
fmt.Printf("call RPC server success, result:%f", result.Value)
}

服务端实现

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
package main

import (
"fmt"
"myphp.org/demorpc/common"
"net/http"
"net/rpc"
)

func main() {
var ms = new(common.MathService)
// 注册 RPC 服务
err := rpc.Register(ms)
if err != nil {
fmt.Printf("rpc server register faild, err:%s", err)
}
// 将 RPC 服务绑定到 HTTP 服务中去
rpc.HandleHTTP()

fmt.Printf("server start ....")
err = http.ListenAndServe(":9090", nil)

if err != nil {
fmt.Printf("listen and server is failed, err:%v\n", err)
}

fmt.Printf("server stop ....")
}

功能实现

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
package common

import "errors"

type Args struct {
A, B float32
}

type Result struct {
Value float32
}

type MathService struct{}

func (s *MathService) Add(args *Args, result *Result) error {
result.Value = args.A + args.B
return nil
}

func (s *MathService) Divide(args *Args, result *Result) error {
if args.B == 0 {
return errors.New("arge.B is 0")
}

result.Value = args.A / args.B
return nil
}

参考

本文主要参考以上文章,一些成果归功于原文作者。