1

【笔记】GRPC 快速入门

 5 months ago
source link: https://loli.fj.cn/2024/03/28/GRPC%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

GRPC 快速入门

go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go get google.golang.org/grpc

编写 Proto 代码

helloword/;golang:配置 Proto 代码存放位置和编译后的语言

syntax = "proto3";

option go_package="helloword/;helloword";

package hello_grpc;

message Req {
string message = 1;
}

message Res {
string message = 1;
}

service HelloGRPC {
rpc SayHi(Req) returns (Res);
}

编译 Proto 代码

helloword/helloword.proto:Proto 代码的存放路径

protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative helloword/helloword.proto
  • 编译完成后会在 Proto 代码的同级目录下生成 helloword.pb.gohelloword_grpc.pb.go 文件
package main

import (
"context"
"fmt"
"google.golang.org/grpc"
"grpcdemo/helloword"
"net"
)

type Server struct {
helloword.UnimplementedHelloGRPCServer
}

func (server *Server) SayHi(context context.Context, request *helloword.Req) (response *helloword.Res, err error) {
fmt.Println(request.GetMessage())
return &helloword.Res{Message: "pong"}, nil
}

func main() {
listen, _ := net.Listen("tcp", "0.0.0.0:8080")
server := grpc.NewServer()
helloword.RegisterHelloGRPCServer(server, new(Server))
server.Serve(listen)
}
package main

import (
"context"
"fmt"
"google.golang.org/grpc"
"grpcdemo/helloword"
)

func main() {
connect, _ := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure())
defer connect.Close()
client := helloword.NewHelloGRPCClient(connect)
response, _ := client.SayHi(context.Background(), &helloword.Req{Message: "ping"})
fmt.Println(response.GetMessage())
}

哔哩哔哩 ——go 圈里最会写 js 的奇淼


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK