grpc环境搭建

一、grpc下载


二、windows下设置

  • protoc环境变量设置
    在这里插入图片描述

  • 在GOPATH的bin目录下找到之前install生成的2个exe文件:拷贝到protoc的bin目录下
    在这里插入图片描述
    在这里插入图片描述

  • grpc的proto生成命令protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative *.proto

    • 最新版本的会生成2个文件
      在这里插入图片描述
  • 对应的版本

    • protoc-gen-go v1.28.0
    • protoc v3.21.2
    • protoc-gen-go-grpc v1.2.0
  • helloworld.proto

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;
}
  • server:注意Server的结构中需要带上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
	}
}

  • client
package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"

	"test_project/grpc_test/proto"
)

func main() {
	//stream
	conn, err := grpc.Dial("127.0.0.1:8088", grpc.WithInsecure())
	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)
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无休止符

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值