google出品的grpc就不需要更多的词汇夸了,毕竟是开发人员的爸爸出的
安装
git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc
git clone https://github.com/golang/net.git $GOPATH/src/golang.org/x/net
git clone https://github.com/golang/text.git $GOPATH/src/golang.org/x/text
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
git clone https://github.com/google/go-genproto.git $GOPATH/src/google.golang.org/genproto
protofile
- 注意函数入参必须是一个message
syntax = "proto3";
package mark;
service Mark {
rpc GetResult(Input) returns(Result) {}
}
message Input {
string src = 4;
string trg = 5;
string inputs = 6;
string kwargs = 7;
}
message Result {
string result = 1;
string errmsg = 2;
int32 errcode = 3;
}
生成代码
protoc --go_out=plugins=grpc:. src/proto/mark/mark.proto
grpc server
package main
import (
"flag"
"fmt"
"github.com/guonaihong/log"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"net"
"os"
"proto/mark"
)
type egrpc struct{}
const pairNamePrefix = "mark-grpc"
func (e *egrpc) GetResult(ctx context.Context, input *mark.Input) (*mark.Result, error) {
fmt.Printf("get result :::%#v\n", input)
return &mark.Result{Result: "hello "}, nil
}
func main() {
sa := flag.String("sa", ":1905", "engine grpc server")
level := flag.String("level", "error", "(opt) the default output log level")
flag.Parse()
l := log.New(*level, pairNamePrefix, os.Stdout)
listen, err := net.Listen("tcp", *sa)
if err != nil {
l.Errorf("mark engine server fail\n")
return
}
s := grpc.NewServer()
mark.RegisterMarkServer(s, &egrpc{})
reflection.Register(s)
if err := s.Serve(listen); err != nil {
l.Errorf("failed to server: %v\n", err)
}
}
grpc client
package main
import (
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"proto/mark"
)
func main() {
conn, err := grpc.Dial("127.0.0.1:1905", grpc.WithInsecure())
if err != nil {
fmt.Printf("%s\n", err)
return
}
defer conn.Close()
c := mark.NewMarkClient(conn)
r, err := c.GetResult(context.Background(), &mark.Input{
Src: "en",
Trg: "zh",
Inputs: "hello world",
Kwargs: "####",
})
fmt.Printf("r = %v, err = %v\n", r, err)
}
网友评论