golang grpc 使用

目录

grpc 主要的好处是可以提供跨语言调用的 grpc

编写 proto 文件

这个在网上有很多教程就不赘述了。
syntax = "proto3";

package proto;

service Server {
    rpc RunCommand(ServerRequest) returns (ServerReplys) {}
    rpc RunShell(ServerRequest) returns (ServerReplys) {}
}


// 执行的命令和执行命令的 IP
message ServerRequest {
  repeated string ips = 1;
  string cmd = 2;
  string user = 3;
}

message ServerReplys {
    repeated ServerReply serverReply = 1;
}

// 服务器执行命令的返回结果
message ServerReply {
    string stdout = 1;
    string stderr = 2;
    string host = 3;
}

生成 go 文件

protoc -I . --go_out=plugins=grpc:. ./master.proto

编写服务端代码

import (
  "net"
  PB "neurons_master/grpc/proto"
  U "github.com/jingminglang/gotools/utils"
  "golang.org/x/net/context"
  "google.golang.org/grpc"
)


type ServerService struct{}
// 实现服务接口
func (s ServerService) RunCommand(ctx context.Context, in *PB.ServerRequest) (*PB.ServerReplys, error) {
......
}

func (s ServerService) RunShell(ctx context.Context, in *PB.ServerRequest) (*PB.ServerReplys, error) {
......
}

// 启动服务代码
func StartRPCServer() bool {
  listen, err := net.Listen("tcp", CF.GrpcListenAddress)
  U.Throw(err)
  s := grpc.NewServer()
  PB.RegisterServerServer(s, ServerService{})
  s.Serve(listen)

  return true
}


编写客户端代码

import (
  PB "neurons_master/grpc/proto"
  "golang.org/x/net/context"
  "google.golang.org/grpc"
  "google.golang.org/grpc/grpclog"
  "google.golang.org/grpc/credentials"
  "crypto/tls"
)



//GrpcClient 全局使用的 grpc 客户端
var GrpcClient = getGrpcClient()

//getGrpcClient 获取 grpc 客户端
func getGrpcClient() PB.ServerClient {
  conn, err := grpc.Dial(CF.GrpcServerAddress, grpc.WithInsecure())

  // creds := credentials.NewTLS( &tls.Config{ InsecureSkipVerify: true } )
  // conn, err := grpc.Dial( CF.GrpcServerAddress, grpc.WithTransportCredentials( creds ) )

  if err != nil {
    grpclog.Fatalln(err)
  }
  c := PB.NewServerClient(conn)
  return c
}

// 调用 server
func RunCommand(ips []string,cmd string) *PB.ServerReplys {
  reqBody := new(PB.ServerRequest)
  reqBody.Ips = ips
  reqBody.Cmd = cmd
  r, err := GrpcClient.RunCommand(context.Background(), reqBody)
  U.Throw(err)
  return r
}


// 调用 server
func RunShell(ips []string,cmd string) *PB.ServerReplys {
  reqBody := new(PB.ServerRequest)
  reqBody.Ips = ips
  reqBody.Cmd = cmd
  r, err := GrpcClient.RunShell(context.Background(), reqBody)
  U.Throw(err)
  return r
}

目录