go语言 grpc入门

what grpc

gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services.


go获取grpc依赖

go get google.golang.org/grpc

入门示例

1.编写.proto描述文件
hello.proto

syntax = "proto3";
package proto;

message String {
    string value = 1;
}

service HelloService {
    rpc Hello (String) returns (String);
}

2.使用protoc工具生成相应的go代码
生成的代码与porto描述文件在同一个目录下,包路径与package对应,文件名为hello.pb.go

3.服务提供者实现定义的rpc方法

package proto

import (
	"context"
	"fmt"
)

type HelloServiceImpl struct {
   

}

func (p *HelloServiceImpl) Hello(ctx context.Context, args *String) (*String, error) {
   
	reply := &String{
   Value: "hello grpc"}

	return reply, nil
}

4.注册grpc服务

package main

import (
	"google.golang.org/grpc"
	proto "let_me_go/protobuf"
	"log"
	"net"
)

func main() {
   
    // 启动一个grpc server
	grpcServer := grpc.NewServer()
	// 绑定服务实现,RegisterHelloServiceServer由protoc根据描述文件生成
	proto.RegisterHelloServiceServer(grpcServer, new(proto.HelloServiceImpl))

	listen, e := net.Listen("tcp", "localhost:8888")

	if e != nil {
   
		log.Fatal(e)
	}

    // 绑定监听端口
	grpcServer.Serve(listen)
}

5.服务端调用grpc服务

package main

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

func main() {
   
    // 监听服务提供端口
	dialConn, _ := grpc.Dial("localhost:8888", grpc.WithInsecure())

	defer dialConn.Close()
    
    // 在监听端口的基础上创建grpc client,NewHelloServiceClient由protoc生成
	client := proto.NewHelloServiceClient(dialConn)
	// 调用rpc方法
	result, _ := client.Hello(context
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值