owenqing 联系🪐

Golang Rpc 基本使用

protoc 编译工具

windows 平台下载对应平台的 protobuf,并配置环境变量
protobuf

linux 环境先安装依赖
sudo apt-get install autoconf automake libtool curl make g++ unzip

git clone https://github.com/google/protobuf.git

cd protobuf
git submodule update --init --recursive
./autogen.sh

# 先到 /usr/local 新建一个目录 protobuf
./configure --prefix=/usr/local/protobuf
make
make check
sudo make install
sudo ldconfig # refresh shared library cache.

protobuf 生成 golang 代码还需要安装 protoc-gen-go
go get -u github.com/golang/protobuf/protoc-gen-go
protoc-gen-go 自动的安装到 $GOPATH/bin 目录下,这个目录需要加入环境变量

pb Demo

创建 proto 目录,用于存放编写好的 xxx.proto 文件,这里是 animal_info.proto

syntax="proto3";
package proto;

// Animal Search Request
message GetAnimalReq {
        int32 id = 1;
}

// Animal Search Response
message GetAnimalRsp {
        string name = 1;
        int32 age = 2;
}

service GetAnimalInfoService {
        rpc GetAnimalInfo (GetAnimalReq) returns (GetAnimalRsp);
}

在目录下创建 compile 文件并添加 protoc --go_out=../pb/ *.proto
给文件加上可执行权限 chmod +x compile
./compile 编译生成 xxx.pb.go 文件

golang rpc

go 语言标准库中实现了一套 rpc,我们来看看用法

server 实现

// 定义一个服务结构体用于绑定具体的方法
type AnimalInfoService struct{}

// pb.xxx 是上个步骤编译 proto 文件生成的 ==> xxx.pb.go
func (ani *AnimalInfoService) GetAnimalInfo(req *pb.GetAnimalReq, resp *pb.GetAnimalRsp) error {
        resp.Name = "Jade"
        resp.Age = 21
        return nil
}

var (
        address = ":9000"
)

func main() {
        // 这里可以注册多个服务,第一个参数是服务的名字
        rpc.RegisterName("AnimalInfoService", new(handler.AnimalInfoService))
        // handle http
        rpc.HandleHTTP()

        httpListen, err := net.Listen("tcp", address)
        CheckError(err)
        http.Serve(httpListen, nil)
}

client 实现

const (
        addrees = "localhost:9000"
)

func main() {
        client, err := rpc.DialHTTP("tcp", addrees)
        if err != nil {
                log.Println("debugxxx")
                log.Fatal(err)
        }

        request := &pb.GetAnimalReq{
                Id: 1,
        }
        var response pb.GetAnimalRsp

        err = client.Call("AnimalInfoService.GetAnimalInfo", request, &response)
        if err != nil {
                log.Fatal(err)
        }
        log.Printf("rpc ==> %v %v\n", response.Name, response.Age)
}
posted @ 2021-02-27 10:18  owenqing  阅读(232)  评论(0)    收藏  举报