grpc damo

grpc流程

在这里插入图片描述

1、下载安装包

安装protobuf

go get -u github.com/golang/protobuf/proto
go get -u github.com/golang/protobuf/protoc-gen-go

安装gRPC

go get -u google.golang.org/grpc

不过由于国内的网络原因上面的命令可能不会成功
执行下面的多条命令来代替

git clone https://github.com/golang/net.git =>$GOPATH/src/golang.org/x/net

git clone https://github.com/golang/text.git =>$GOPATH/src/golang.org/x/text

git clone https://github.com/google/go-genproto.git =>$GOPATH/src/google.golang.org/genproto

git clone https://github.com/grpc/grpc-go.git =>$GOPATH/src/google.golang.org/grpc

git clone https://github.com/protocolbuffers/protobuf-go.git =>$GOPATH/src/google.golang.org/protobuf

注:go版本再1.5以上

2、protobuf文件

helloword.proto

syntax = "proto3";

package helloworld;

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

message HelloRequest{
    string name = 1;
}

message HelloReply{
    string message = 1;
}

3、编译protobuf 文件

protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
-I  path1 path2 --go_out=plugins=grpc:path3
path1:搜索哪个目录(当前目录的相对路径)
path2:使用哪个proto文件(当前目录的相对路径)
path3:编译转换的.go文件放置的路径(当前目录的相对位置)

使用docker编译

docker run namely/protoc-all
docker run -v ${PWD}:/defs namely/protoc-all -o interface -f proto/user.proto -l go
-o 指定输出文件
-f 指定proto文件

https://github.com/namely/docker-protoc

4、服务端编写

package main

import (
	"context"
	fmt "fmt"
	"google.golang.org/grpc"
	"grpc_test/helloworld"
	"net"
)

type server struct{}

// 实现接口
func (s *server)SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error){
	r := helloworld.HelloReply{}
	fmt.Println(in.Name)
	r.Message = fmt.Sprintf("hello %s", in.Name)
	return &r,nil
}

const listen_port = "127.0.0.1:50021"

func main(){
	// net.listen监听
	listen,err := net.Listen("tcp",listen_port)
	if err != nil{
		fmt.Println("listen fail")
	}
	//new server
	s := grpc.NewServer()
	//register server       注:context.Background()是空context
	helloworld.RegisterGreeterServer(s,&server{})
	// 接收处理
	err = s.Serve(listen)
	if err != nil{
		fmt.Println("server fail")
	}
}

5、客户端编写

package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"grpc_test/helloworld"
)

const conn_port = "127.0.0.1:50021"

func main(){
	// 建立连接
	conn,err := grpc.Dial(conn_port,grpc.WithInsecure())
	if err != nil{
		fmt.Println("con fail")
	}
	// 获取客户端对象
	client := helloworld.NewGreeterClient(conn)
	// 客户端处理
	res,err := client.SayHello(context.Background(),&helloworld.HelloRequest{
		Name: "lqh",
	})
	if err != nil{
		fmt.Println("sayhello fail")
	}
	fmt.Println(res)
}

6、protobuf语法

https://lioncat.blog.csdn.net/article/details/106824403

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值