go语言下的grpc开发

1、下载protoc

地址:https://github.com/google/protobuf/releases

window:
    下载: protoc-3.3.0-win32.zip
    解压,把bin目录下的protoc.exe复制到GOPATH/bin下,GOPATH/bin加入环境变量。
    当然也可放在其他目录,需加入环境变量,能让系统找到protoc.exe
linux:
    下载:protoc-3.3.0-linux-x86_64.zip 或 protoc-3.3.0-linux-x86_32.zip
    解压,把bin目录下的protoc复制到GOPATH/bin下,GOPATH/bin加入环境变量。
    如果喜欢编译安装的,也可下载源码自行安装,最后将可执行文件加入环境变量。

2、下载go的依赖包

  命令:go get -u github.com/golang/protobuf/protoc-gen-go

3、创建protoc文件

  goland安装proto support插件教程:(29条消息) Gland安装 protobuf Support 插件_劉小五的博客-CSDN博客_goland protobuf support

4、生成go文件

  参考:(29条消息) golang_protoc: protoc编译生成pb.go文件_Grayan的博客-CSDN博客_protoc 生成pb文件

  proto文件内容:

syntax = "proto3";

package hello;

option go_package = ".;proto";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

 生成命令改为:protoc -I . hello.proto --go_out=plugins=grpc:.

5、代码

服务端代码

package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"server/proto"
	"net"
)

type Server struct {
}


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()
	s := Server{}
	proto.RegisterGreeterServer(g,&s)
	lis, err := net.Listen("tcp", fmt.Sprintf(":8080"))
	if err != nil {
		panic("failed to listen: "+err.Error())
	}
	g.Serve(lis)
}

客户端代码

package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"client/proto"
)

func main()  {
	conn,err := grpc.Dial("127.0.0.1:8080",grpc.WithInsecure())
	if err!=nil{
		panic(err)
	}
	defer conn.Close()
	c := proto.NewGreeterClient(conn)
	r,err := c.SayHello(context.Background(),&proto.HelloRequest{Name:"bobby"})
	if err!=nil{
		panic(err)
	}
	fmt.Println(r.Message)
}

  

 

posted @ 2022-04-26 10:33  ☞@_@  阅读(46)  评论(0编辑  收藏  举报