golang 进行grpc调用
2024-09-05 03:31:55
参考https://blog.csdn.net/qq_32744005/article/details/105606383
go get google.golang.org/grpc
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
[root@localhost helloworld]# echo $GOPATH
/usr/local/go/workspacego
cd /usr/local/go/workspacego/src/google.golang.org/grpc/examples/helloworld/helloworld
[root@localhost helloworld]# cat /data/wwwroot/grpcdemo/client.go
package main import (
"context"
"log"
"os"
"time"
"google.golang.org/grpc" //grpc 的包
pb "google.golang.org/grpc/examples/helloworld/helloworld" //生产的中间文件
) const (
address = "localhost:50051" //ip + port
defaultName = "world"
) func main() {
// Set up a connection to the server.
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn) // Contact the server and print out its response.
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.GetMessage())
}
[root@localhost helloworld]# cat /data/wwwroot/grpcdemo/server.go
package main import (
"context"
"log"
"net" "google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
) const (
port = ":50051"
) // server is used to implement helloworld.GreeterServer.
type server struct {
pb.UnimplementedGreeterServer
} // SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.GetName())
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
} func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
#go run /data/wwwroot/grpcdemo/server.go
另外发起一个终端
#go run /data/wwwroot/grpcdemo/client.go
服务端返回
2020/05/12 17:33:56 Received: world
客户端返回
2020/05/12 17:33:56 Greeting: Hello world
最新文章
- 在WebBrowser中截获弹出对话框内容并将其屏蔽
- Android中的几种解析XML文件的类
- PoEdu - C++阶段班- Lesson02_C to C++
- js 立即执行函数,() .则前面的function 是表达式,不能是函数申明
- linux locate: command not found
- [置顶] Codeforces Round #198 (Div. 1)(A,B,C,D)
- setjmp/longjmp 使用
- cf459C Pashmak and Buses
- Object-c学习之路二(oc内存管理黄金法则1)
- PCB设计检查
- 【codelife 阿里技术文章分享——读后感】
- python note 16 re模块的使用
- PHP+XML写注册登录
- vue IE 报错 引用babel-polyfill
- C++Primer第五版——习题答案详解(一)
- weblogic11,linux字符页面安装
- solr系统query检索词特殊字符的处理
- APP-9.1-百度应用-文字识别
- VS 2013 中如何自定义快捷键(图解)
- HDU 1075 What Are You Talking About (strings)