gRPC 1 helloworld go-lang

运行起来的话大概是这样

从零开始

1. 先安装 golang

sudo apt install golang

添加环境变量

export GOROOT=/usr/lib/go
export GOPATH=$HOME/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOROOT:$GOPATH:$GOBIN

2. 安装git

sudo apt install git

3. 安装 grpc 依赖

go get -u github.com/golang/protobuf/protoc-gen-go

4. 添加 go.mod 文件

module helloworld

require (
    google.golang.org/grpc v1.29.1
    google.golang.org/protobuf v1.25.0
)

go 1.13
 

5. 安装 protoc 工具

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

./configure

make

make check

sudo make install

sudo ldconfig

protoc –version

切换到项目工作目录

cd grpc_go/

创建文件/home/lizhe/works/grpc_go/pbfiles/Hi.proto

syntax="proto3";  //
package services;
option go_package = "../services";
message HiRequest {
  string say = 1;
}
message HiResponse {
  string responed = 1;
}
service HiService {
    rpc GetHiResponed(HiRequest) returns (HiResponse);
}

切换到 pbfiles 文件夹

cd pbfiles

protoc –go_out=plugins=grpc:. Hi.proto

会生成 /home/lizhe/works/grpc_go/services/Hi.pb.go

创建文件 /home/lizhe/works/grpc_go/services/HiService.go

package services

import (
    "context"
    "fmt"
)

type HiService struct {
}

func (hs HiService) GetHiResponed(ctx context.Context, request *HiRequest) (*HiResponse, error) {
    fmt.Println("Say:" + request.Say)
    return &HiResponse{Responed: "helloworld"}, nil
}

创建 server.go

package main

import (
    "helloworld/services"
    "net"

    "google.golang.org/grpc"
)

func main() {
    rpcServer := grpc.NewServer()                                        // 创建grpc服务
    services.RegisterHiServiceServer(rpcServer, new(services.HiService)) // 注册,new方法中的是services包中定义的结构体HiService
    lis, _ := net.Listen("tcp", ":8081")                                 // 开启一个监听端口
    rpcServer.Serve(lis)                                                 // 启动服务
}
 

创建 client.go

package main

import (
    "context"
    "fmt"
    "helloworld/services"
    "log"

    "google.golang.org/grpc"
)

func main() {

    conn, err := grpc.Dial(":8081", grpc.WithInsecure())
    if err != nil {
        log.Println(err)
    }
    defer conn.Close()
    client := services.NewHiServiceClient(conn)
    resp, err := client.GetHiResponed(context.Background(), &services.HiRequest{Say: "Hello"})
    if err != nil {
        log.Println(err)
    }
    fmt.Println(resp.Responed)

}