syntax = "proto3";
package proto; //当前包名
option go_package = "./";
message HelloRequest{
string name = 1; // 1是编号不是值
}
package main
import (
"encoding/json"
"fmt"
"github.com/golang/protobuf/proto"
"MyTestProject/helloworld/proto"
)
type Hello struct {
Name string `json:"name"`
}
func main() {
req := __.HelloRequest{
Name: "test",
}
rsp, _ := proto.Marshal(&req)
fmt.Println("proto len = ", len(rsp))
jsonStruct := Hello{Name: "test"}
jsonRsp, _ := json.Marshal(jsonStruct)
fmt.Println("json len = ", len(jsonRsp))
}
syntax = "proto3";
package proto; //当前包名
option go_package = "./";
message HelloRequest{
string name = 1; // 1是编号不是值
int32 age = 2;
repeated string courses = 3; //repeated代表可重复的,切片
}
package main
import (
"encoding/json"
"fmt"
"github.com/golang/protobuf/proto"
"MyTestProject/helloworld/proto"
)
type Hello struct {
Name string `json:"name"`
Age int `json:"age"`
Courses []string `json:"courses"`
}
func main() {
req := __.HelloRequest{
Name: "test",
Age: 18,
Courses: []string{"go", "gin", "微服务"},
}
rsp, _ := proto.Marshal(&req)
fmt.Println("proto len = ", len(rsp))
jsonStruct := Hello{
Name: "test",
Age: 18,
Courses: []string{"go", "gin", "微服务"},
}
jsonRsp, _ := json.Marshal(jsonStruct)
fmt.Println("json len = ", len(jsonRsp))
}
package main
import (
"fmt"
"github.com/golang/protobuf/proto"
"MyTestProject/helloworld/proto"
)
func main() {
req := __.HelloRequest{
Name: "test",
Age: 18,
Courses: []string{"go", "gin", "微服务"},
}
rsp, _ := proto.Marshal(&req)
fmt.Println("proto len = ", len(rsp))
// 反序列化proto
newReq := __.HelloRequest{}
_ = proto.Unmarshal(rsp, &newReq)
fmt.Println(newReq.Name, newReq.Age, newReq.Courses)
}
syntax = "proto3";
package proto; //当前包名
option go_package = "./";
service Hello{
rpc Hello(HelloRequest) returns (Response); // hello接口
}
message HelloRequest{
string name = 1; // 1是编号不是值
int32 age = 2;
repeated string courses = 3; //repeated代表可重复的,切片
}
message Response{
string reply = 1;
}
protoc --go-grpc_out=. *.proto
(这个就是为什么在grpc环境搭建中我们需要下载与修改protoc-gen-go-grpc.exe这个文件)syntax = "proto3";
option go_package = ".;proto";
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
proto.UnimplementedGreeterServer
否则会报错package main
import (
"context"
"net"
"google.golang.org/grpc"
"test_project/grpc_test/proto"
)
type Server struct{
proto.UnimplementedGreeterServer
}
func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply,
error) {
return &proto.HelloReply{
Message: "hello " + request.Name,
}, nil
}
func main() {
g := grpc.NewServer()
proto.RegisterGreeterServer(g, &Server{})
lis, err := net.Listen("tcp", "0.0.0.0:8088")
if err != nil {
return
}
err = g.Serve(lis)
if err != nil {
return
}
}
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"test_project/grpc_test/proto"
)
func main() {
conn, err := grpc.Dial("127.0.0.1:8088", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return
}
defer conn.Close()
c := proto.NewGreeterClient(conn)
r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "test"})
if err != nil {
return
}
fmt.Println(r.Message)
}
grpc有四种流模式:
stream.proto
syntax = "proto3";
option go_package = ".;proto";
service Greeter {
rpc GetStream(StreamReqData) returns (stream StreamResData); //服务端流模式
rpc PutStream(stream StreamReqData) returns (StreamResData); //客户端流模式
rpc AllStream(stream StreamReqData) returns (stream StreamResData); //双向流模式
}
message StreamReqData {
string data = 1;
}
message StreamResData {
string data = 1;
}
package main
import (
"fmt"
"net"
"sync"
"time"
"google.golang.org/grpc"
"test_project/stream_grpc_test/proto"
)
const PORT = ":50052"
type server struct {
proto.UnimplementedGreeterServer
}
func (s *server) GetStream(req *proto.StreamReqData, res proto.Greeter_GetStreamServer) error {
i := 0
for {
i++
_ = res.Send(&proto.StreamResData{
Data: fmt.Sprintf("%v", time.Now().Unix()),
})
time.Sleep(time.Second)
if i > 10 {
break
}
}
return nil
}
func (s *server) PutStream(cliStr proto.Greeter_PutStreamServer) error {
for {
if a, err := cliStr.Recv(); err != nil {
fmt.Println(err)
break
} else {
fmt.Println(a.Data)
}
}
return nil
}
func (s *server) AllStream(allStr proto.Greeter_AllStreamServer) error {
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
for {
data, _ := allStr.Recv()
fmt.Println("收到客户端消息:" + data.Data)
}
}()
go func() {
defer wg.Done()
for {
_ = allStr.Send(&proto.StreamResData{Data: "我是服务器"})
time.Sleep(time.Second)
}
}()
wg.Wait()
return nil
}
func main() {
lis, err := net.Listen("tcp", PORT)
if err != nil {
return
}
s := grpc.NewServer()
proto.RegisterGreeterServer(s, &server{})
err = s.Serve(lis)
if err != nil {
return
}
}
package main
import (
"context"
"fmt"
"google.golang.org/grpc/credentials/insecure"
"sync"
"time"
"google.golang.org/grpc"
"test_project/stream_grpc_test/proto"
)
func main() {
conn, err := grpc.Dial("localhost:50052", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return
}
defer conn.Close()
//服务端流模式
c := proto.NewGreeterClient(conn)
res, _ := c.GetStream(context.Background(), &proto.StreamReqData{Data: "学习"})
for {
a, err := res.Recv() //如果大家懂socket编程的话就明白 send recv
if err != nil {
fmt.Println(err)
break
}
fmt.Println(a.Data)
}
//客户端流模式
putS, _ := c.PutStream(context.Background())
i := 0
for {
i++
_ = putS.Send(&proto.StreamReqData{
Data: fmt.Sprintf("学习%d", i),
})
time.Sleep(time.Second)
if i > 10 {
break
}
}
//双向流模式
allStr, _ := c.AllStream(context.Background())
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
for {
data, _ := allStr.Recv()
fmt.Println("收到客户端消息:" + data.Data)
}
}()
go func() {
defer wg.Done()
for {
_ = allStr.Send(&proto.StreamReqData{Data: "学习"})
time.Sleep(time.Second)
}
}()
wg.Wait()
}