go grpc 使用案例

作者: adm 分类: go 发布时间: 2022-09-29

1.创建 .proto文件

syntax = "proto3";

option go_package="/proto";

package Business;

service Hello {
  rpc Say (SayRequest) returns (SayResponse);
}

message SayResponse {
  bytes Resp = 1;
}

message SayRequest {
  string Name = 1;
}

2.代码生成命令

protoc --go_out=./ ./hello.proto
protoc --go-grpc_out=./  hello.proto

前提条件是必须下载protoc.exeprotoc-gen-go.exe 并且加入环境变量,

3.代码
service代码:

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"grpchello/proto"
	"net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

type server struct {
	proto.UnimplementedHelloServer
}

func (s *server) Say(ctx context.Context, req *proto.SayRequest) (*proto.SayResponse, error) {
	fmt.Println("request:", req.Name)
	var aa []string
	aa = append(aa, "nn", "hh")

	r := make(map[string]any, 0)
	r["code"] = 200
	r["message"] = "ok"
	r["result"] = aa
	ee, _ := json.Marshal(r)
	return &proto.SayResponse{Resp: ee}, nil
}

func main() {
	listen, err := net.Listen("tcp", ":8001")
	if err != nil {
		fmt.Printf("failed to listen: %v", err)
		return
	}
	s := grpc.NewServer()
	proto.RegisterHelloServer(s, &server{})
	reflection.Register(s)

	defer func() {
		s.Stop()
		listen.Close()
	}()

	fmt.Println("Serving 8001...")
	err = s.Serve(listen)
	if err != nil {
		fmt.Printf("failed to serve: %v", err)
		return
	}
}

client

package main
 
import (
	"context"
	"log"
	"google.golang.org/grpc"
	pb "protobuf/grpc/hello"
)
 
const (
	address     = "127.0.0.1:8080"
)
 
func main() {
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("客户端连接异常: %v", err)
	}
	defer conn.Close()
 
	c := pb.NewHelloserverClient(conn)//获取GRPC句柄
 
	r, err := c.SayHello(context.Background(), &pb.HelloRequest{
		Name: "哈哈",
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("####### get server Greeting response: %s", r.Message)
}
go run grpc_server.go
go run grpc_client.go

返回

{"code":200,"message":"ok","result":["nn","hh"]}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!