go grpc 初步笔记

为什么80%的码农都做不了架构师?>>>   hot3.png

GRPC

像许多RPC系统一样,gRPC基于定义服务的思想,指定可以使用其参数和返回类型远程调用的方法。

特点

  1. 基于 HTTP/2, 继而提供了连接多路复用、Body 和 Header 压缩等机制。可以节省带宽、降低TCP链接次数、节省CPU使用和延长电池寿命等。
  2. 支持主流开发语言(C, C++, Python, PHP, Ruby, NodeJS, C#, Objective-C、Golang、Java)
  3. IDL (Interface Definition Language) 层使用了 Protocol Buffers, 非常适合团队的接口设计

安装

安装grpc

grpc/grpc-go

GEPC Go Quick Start

go get google.golang.org/grpc

因为被墙,所以有可能需要其他方式

由于墙的原因,我们一些依赖的包文件可以通过下面方式下载到:

在 github 可以找到源码,下载后复制到对应目录即可的:

  • google.golang.org/grpc 对应的代码地址在: https://github.com/grpc/grpc-go
  • google.golang.org/cloud/compute/metadata 对应的代码地址在: https://github.com/GoogleCloudPlatform/gcloud-golang
  • golang.org/x/oauth2 对应的代码地址在: https://github.com/golang/oauth2
  • golang.org/x/net/context 对应的代码地址在: https://github.com/golang/net

这些包的源码也可以通过 http://gopm.io/ 或者 http://golangtc.com/download/package 进行下载.

go get –a 这样的命令, –a 参数是go install的参数,不是go get的参数。

参考: https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/01.3.md

gRPC的简单Go例子

安装protobuf

google protobuf 如果使用go开发安装下面那个

google/protobuf

protobuf 指南

go 开发使用的protobuf

golang/protobuf

//安装protobuf
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}

//没安装成功这个protoc-gen-go再安装一下这个
go get -a github.com/golang/protobuf/protoc-gen-go

安装protoc

下载使用protoc工具 google/protobuf

windows 下载 protoc-3.2.0-win32.zip 类似这样的包

其他系统下载自己系统的包

使用注意事项

到我写博客的时候,grpc使用protobuffer生成文件的context 依然使用的是"golang.org/x/net/context" 而不是使用的 $GOPATH/context, 这个需要在使用的时候注意,自己server和clinet 引入的时候也必须用"golang.org/x/net/context",需要等后续官方更新后,可能会进行修改。

官方Replace "golang.org/x/net/context" with "context" and stop supporting go1.6 还是打开状态。

hello world

官方hello.proto文件


syntax = "proto3";

//这3个可以删掉,暂时不清楚又什么作用应该是java里相关的。
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";

package helloworld;

// 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;
}

将这个文件放置pb文件夹,然后在这个文件夹中输入命令:

protoc --go_out=. *.proto

将会生成 hello.pb.go文件,这个时候我们的服务端和客户端就可以使用这个文件了。

服务端:

package main

import (
	"log"
	"net"

	"golang.org/x/net/context"
	"google.golang.org/grpc"
	pb "google.golang.org/grpc/examples/helloworld/helloworld"
	"google.golang.org/grpc/reflection"
)

const (
	port = ":50051"
)

// server is used to implement helloworld.GreeterServer.
type server struct{}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}

func main() {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})
	// Register reflection service on gRPC server.
	reflection.Register(s)
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

客户端

package main

import (
	"log"
	"os"

	"golang.org/x/net/context"
	"google.golang.org/grpc"
	pb "google.golang.org/grpc/examples/helloworld/helloworld"
)

const (
	address     = "localhost:50051"
	defaultName = "world"
)

func main() {
	// Set up a connection to the server.
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c := pb.NewGreeterClient(conn)

	// Contact the server and print out its response.
	name := defaultName
	if len(os.Args) > 1 {
		name = os.Args[1]
	}
	r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r.Message)
}

有了文件以后就可以运行进行测试了

go run server/main.go
go run client/main.go

增加一个新方法

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // Sends another greeting
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}


然后使用命令

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

服务端添加

func (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
        return &pb.HelloReply{Message: "Hello again " + in.Name}, nil
}

客户端添加

r, err = c.SayHelloAgain(context.Background(), &pb.HelloRequest{Name: name})
if err != nil {
        log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)

运行结果出现

2017/03/30 17:06:46 Greeting: Hello world
2017/03/30 17:06:46 Greeting: Hello again world

下一篇:go grpc 深入笔记

参考

gRPC Basics - Go

gRPC初体验

gRPC Android SSL/TLS Demo(Android上带有SSL/TLS加密的gRPC使用详解)

gRPC Basics - Go

PS: 觉得不错的请点个赞吧!! (ง •̀_•́)ง

转载于:https://my.oschina.net/solate/blog/870675

你可能感兴趣的:(go grpc 初步笔记)