1 go grpc-go 相关技术专栏 总入口
2 Protobuf介绍与实战 图文专栏 文章目录
1、在proto文件里定义rpc方法时,如何实现无参数设置、无返回值设置呢? |
1.2、第2步:设置方法为无参数设置、无返回值设置 |
syntax = "proto3";
import "google/protobuf/empty.proto";
package proto;
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
service Greeter {
// 模拟1:没有返回值 情况
rpc SayHello1 (HelloRequest) returns (google.protobuf.Empty) {}
// 模拟2:没有参数 情况
rpc SayHello2 (google.protobuf.Empty) returns (HelloReply) {}
// 模拟3:没有参数,没有返回值 情况
rpc SayHello3 (google.protobuf.Empty) returns (google.protobuf.Empty) {}
}
可以通过类似下面的命令,生成指定的文件:
protoc --go_out=. --go-grpc_out=. helloworld.proto
package main
import (
"context"
"fmt"
"github.com/CodisLabs/codis/pkg/utils/log"
"github.com/golang/protobuf/ptypes/empty"
"google.golang.org/grpc"
"grpc-go-study/grpc-other/test_empty/proto"
"net"
)
const (
port = ":50051"
)
type server struct {
proto.UnimplementedGreeterServer
}
func (s *server) SayHello1(context.Context, *proto.HelloRequest) (*empty.Empty, error) {
fmt.Println("--->this is SayHello1<---")
return &empty.Empty{}, nil
}
func (s *server) SayHello2(context.Context, *empty.Empty) (*proto.HelloReply, error) {
fmt.Println("--->this is SayHello2<---")
return &proto.HelloReply{
Message: "--->this is SayHello2<---",
}, nil
}
func (s *server) SayHello3(context.Context, *empty.Empty) (*empty.Empty, error) {
fmt.Println("--->this is SayHello3<---")
return &empty.Empty{}, nil
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Errorf("failed to listen: %v", err)
}
s := grpc.NewServer()
proto.RegisterGreeterServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Errorf("failed to serve: %v", err)
}
}
package main
import (
"context"
"github.com/CodisLabs/codis/pkg/utils/log"
"github.com/golang/protobuf/ptypes/empty"
"google.golang.org/grpc"
"grpc-go-study/grpc-other/test_empty/proto"
)
const (
address = "localhost:50051"
defaultName = "---helloworld---"
)
func main() {
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Errorf("did not connect: %v", err)
panic(err)
}
defer conn.Close()
c := proto.NewGreeterClient(conn)
ctx := context.Background()
msgEmpty, err := c.SayHello1(ctx, &proto.HelloRequest{Name: defaultName})
if err != nil {
panic(err.Error())
}
log.Infof("SayHello1\tresult:%s", msgEmpty.String())
msgResp, err := c.SayHello2(ctx, &empty.Empty{})
if err != nil {
panic(err.Error())
}
log.Infof("SayHello2\tresult:%s", msgResp.String())
msgEmpty, err = c.SayHello3(ctx, &empty.Empty{})
if err != nil {
panic(err.Error())
}
log.Infof("SayHello3\tresult:%s", msgEmpty.String())
}
下一篇文章
Protobuf 类名、属性大小写是否有影响?
评论列表(0条)