grpc相关材料
Go中的gRPC入门详解 - it610.com
gRPC grpc文档手册
【Go语言实战】(9) gRPC 实现一个简单微服务_小生凡一的博客-CSDN博客 (示例已过时)
GitHub - WanshanTian/GolangLearning (最新示例)
实战01
该实战主要是临摹 一凡小生的文章: 【Go语言实战】(9) gRPC 实现一个简单微服务_小生凡一的博客-CSDN博客
但其中的一些步骤是有出入的。
【Golang | gRPC】protocol buffer compiler\protoc的安装_田土豆的博客-CSDN博客 安装protoc 编译器。
【Golang | gRPC】使用protoc编译.proto文件_田土豆的博客-CSDN博客_protoc编译 安装protoc针对golang的插件 protoc-gen-go 和protoc-gen-go-grpc。
示例结果 https://github.com/pro911/godemo/tree/main/grpc01
版本
- go 1.17
go version
go version go1.17.10 windows/amd64
- protoc
protoc --version
libprotoc 3.19.4
- protoc-gen-go-grpc
protoc-gen-go-grpc --version
protoc-gen-go-grpc 1.2.0
- protoc-gen-go --version
protoc-gen-go --version
protoc-gen-go.exe v1.28.0
#老版本 生成一个user.pb.go文件
protoc --go_out=plugins=grpc:./ ./user.proto # 生成go文件
#新版本 生成两个文件user.pb.go 和 user_grpc.pb.go文件 其实就是把内容拆分了以及优化了一些细节。
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative ./user.proto
#新版本 或者
protoc --go_out=. --go-grpc_out=. ./user.proto
#说明示例
protoc --go_out=. --go-grpc_out=. ./hello.proto,生成对应的.pb.go和_grpc.pb.go两个文件,前者主要是对message生成对应的结构体和方法,后者生成gRPC,主要是对service生成对应的interface和方法
go_out=.
指定生成的pb.go
文件所在目录(如果没有该目录,需要手动提前创建),.
代表当前protoc
执行目录,结合.proto
文件中的option go_package
,其最终的生成文件目录为go_out
指定目录/go_package
指定目录。go-grpc_out
针对_grpc.pb.go
文件,作用同上。- 另外官网文档里还有一个
--go_opt=paths=source_relative
,其含义代表生成的.pb.go
文件路径不依赖于.proto
文件中的option go_package
配置项,直接在go_out
指定的目录下生成.pb.go
文件(.pb.go
文件的package
名还是由option go_package
决定)。 --go-grpc_opt=paths=source_relative
,针对_grpc.pb.go
文件,作用同上。
总结
- 打开两个shell窗口 分别运行
go run server.go
和go run client.go
- 客户端会输出:
响应结果 id:1 name:"zs" age:19 hobby:"FanOne" hobby:"FanOneTwo"
代码展示
- 一下代码路径均在grpc01 目录下。
- 根据
user.proto
生成go文件的执行位置在grpc01/proto/
目录下。proto --go_out=./ --go-grpc_out=. ./user.proto
。- 执行启动在
grpc01
目录下。go run server.go
和go run client.go
。
//一个message类型定义描述了一个请求或响应的消息格式,可以包含多种类型字段
//字段名用小写,转为go文件后自动变成大写,message就相当于结构体
//定义版本号
syntax = "proto3";
//定义生成的包名称 : 指定生成user.pb.go包名为proto
package proto;
//输出路径
option go_package = "./";
//定义客户端请求格式
message UserRequest{
//定义请求参数
string name = 1;
}
//定义服务端响应格式
message UserResponse{
//定义响应参数
int32 id = 1;
string name = 2;
int32 age = 3;
//字段修饰符
//repeated 表示可变数组,类似于切片类型
repeated string hobby = 4;
}
//定义服务接口。相当于接口,service相当于开发调用的服务
service UserInfoService{
//接口内的方法
//定义请求参数为UserRequest,响应参数为UserResponse
rpc GetUserInfo (UserRequest) returns (UserResponse) {
}
}
//protoc --go_out=plugins=grpc:. user.proto
//有时候执行上面会报错,是因为版本问题。
//protoc --go_out=. user.proto
//一个message类型定义描述了一个请求或响应的消息格式,可以包含多种类型字段
//字段名用小写,转为go文件后自动变成大写,message就相当于结构体
//定义版本号
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.0
// protoc v3.19.4
// source: user.proto
//定义生成的包名称 : 指定生成user.pb.go包名为proto
package __
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
//定义客户端请求格式
type UserRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
//定义请求参数
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
}
func (x *UserRequest) Reset() {
*x = UserRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_user_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UserRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UserRequest) ProtoMessage() {}
func (x *UserRequest) ProtoReflect() protoreflect.Message {
mi := &file_user_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UserRequest.ProtoReflect.Descriptor instead.
func (*UserRequest) Descriptor() ([]byte, []int) {
return file_user_proto_rawDescGZIP(), []int{0}
}
func (x *UserRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
//定义服务端响应格式
type UserResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
//定义响应参数
Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
Age int32 `protobuf:"varint,3,opt,name=age,proto3" json:"age,omitempty"`
//字段修饰符
//repeated 表示可变数组,类似于切片类型
Hobby []string `protobuf:"bytes,4,rep,name=hobby,proto3" json:"hobby,omitempty"`
}
func (x *UserResponse) Reset() {
*x = UserResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_user_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UserResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UserResponse) ProtoMessage() {}
func (x *UserResponse) ProtoReflect() protoreflect.Message {
mi := &file_user_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UserResponse.ProtoReflect.Descriptor instead.
func (*UserResponse) Descriptor() ([]byte, []int) {
return file_user_proto_rawDescGZIP(), []int{1}
}
func (x *UserResponse) GetId() int32 {
if x != nil {
return x.Id
}
return 0
}
func (x *UserResponse) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *UserResponse) GetAge() int32 {
if x != nil {
return x.Age
}
return 0
}
func (x *UserResponse) GetHobby() []string {
if x != nil {
return x.Hobby
}
return nil
}
var File_user_proto protoreflect.FileDescriptor
var file_user_proto_rawDesc = []byte{
0x0a, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x22, 0x21, 0x0a, 0x0b, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x5a, 0x0a, 0x0c, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01,
0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02,
0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x67,
0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x67, 0x65, 0x12, 0x14, 0x0a, 0x05,
0x68, 0x6f, 0x62, 0x62, 0x79, 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x05, 0x68, 0x6f, 0x62,
0x62, 0x79, 0x32, 0x4b, 0x0a, 0x0f, 0x55, 0x73, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x53, 0x65,
0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x38, 0x0a, 0x0b, 0x47, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72,
0x49, 0x6e, 0x66, 0x6f, 0x12, 0x12, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x55, 0x73, 0x65,
0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x2e, 0x55, 0x73, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42,
0x04, 0x5a, 0x02, 0x2e, 0x2f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_user_proto_rawDescOnce sync.Once
file_user_proto_rawDescData = file_user_proto_rawDesc
)
func file_user_proto_rawDescGZIP() []byte {
file_user_proto_rawDescOnce.Do(func() {
file_user_proto_rawDescData = protoimpl.X.CompressGZIP(file_user_proto_rawDescData)
})
return file_user_proto_rawDescData
}
var file_user_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_user_proto_goTypes = []interface{}{
(*UserRequest)(nil), // 0: proto.UserRequest
(*UserResponse)(nil), // 1: proto.UserResponse
}
var file_user_proto_depIdxs = []int32{
0, // 0: proto.UserInfoService.GetUserInfo:input_type -> proto.UserRequest
1, // 1: proto.UserInfoService.GetUserInfo:output_type -> proto.UserResponse
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_user_proto_init() }
func file_user_proto_init() {
if File_user_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_user_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UserRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_user_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UserResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_user_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_user_proto_goTypes,
DependencyIndexes: file_user_proto_depIdxs,
MessageInfos: file_user_proto_msgTypes,
}.Build()
File_user_proto = out.File
file_user_proto_rawDesc = nil
file_user_proto_goTypes = nil
file_user_proto_depIdxs = nil
}
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v3.19.4
// source: user.proto
package __
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// UserInfoServiceClient is the client API for UserInfoService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type UserInfoServiceClient interface {
//接口内的方法
//定义请求参数为UserRequest,响应参数为UserResponse
GetUserInfo(ctx context.Context, in *UserRequest, opts ...grpc.CallOption) (*UserResponse, error)
}
type userInfoServiceClient struct {
cc grpc.ClientConnInterface
}
func NewUserInfoServiceClient(cc grpc.ClientConnInterface) UserInfoServiceClient {
return &userInfoServiceClient{cc}
}
func (c *userInfoServiceClient) GetUserInfo(ctx context.Context, in *UserRequest, opts ...grpc.CallOption) (*UserResponse, error) {
out := new(UserResponse)
err := c.cc.Invoke(ctx, "/proto.UserInfoService/GetUserInfo", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// UserInfoServiceServer is the server API for UserInfoService service.
// All implementations must embed UnimplementedUserInfoServiceServer
// for forward compatibility
type UserInfoServiceServer interface {
//接口内的方法
//定义请求参数为UserRequest,响应参数为UserResponse
GetUserInfo(context.Context, *UserRequest) (*UserResponse, error)
mustEmbedUnimplementedUserInfoServiceServer()
}
// UnimplementedUserInfoServiceServer must be embedded to have forward compatible implementations.
type UnimplementedUserInfoServiceServer struct {
}
func (UnimplementedUserInfoServiceServer) GetUserInfo(context.Context, *UserRequest) (*UserResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetUserInfo not implemented")
}
func (UnimplementedUserInfoServiceServer) mustEmbedUnimplementedUserInfoServiceServer() {}
// UnsafeUserInfoServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to UserInfoServiceServer will
// result in compilation errors.
type UnsafeUserInfoServiceServer interface {
mustEmbedUnimplementedUserInfoServiceServer()
}
func RegisterUserInfoServiceServer(s grpc.ServiceRegistrar, srv UserInfoServiceServer) {
s.RegisterService(&UserInfoService_ServiceDesc, srv)
}
func _UserInfoService_GetUserInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UserRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserInfoServiceServer).GetUserInfo(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/proto.UserInfoService/GetUserInfo",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserInfoServiceServer).GetUserInfo(ctx, req.(*UserRequest))
}
return interceptor(ctx, in, info, handler)
}
// UserInfoService_ServiceDesc is the grpc.ServiceDesc for UserInfoService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var UserInfoService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "proto.UserInfoService",
HandlerType: (*UserInfoServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetUserInfo",
Handler: _UserInfoService_GetUserInfo_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "user.proto",
}
package main
import (
"context"
"fmt"
pb "github.com/pro911/godemo/grpc01/proto"
"google.golang.org/grpc"
"net"
)
type UserInfoService struct {
pb.UnimplementedUserInfoServiceServer
}
var u = UserInfoService{}
// 实现服务端需要实现的端口
func (service *UserInfoService) GetUserInfo(ctx context.Context, req *pb.UserRequest) (resp *pb.UserResponse, err error) {
name := req.Name
// 在数据库查询用户信息
if name == "zs" {
resp = &pb.UserResponse{
Id: 1,
Name: name,
Age: 19,
// 切片字段
Hobby: []string{"FanOne", "FanOneTwo"},
}
}
err = nil
return
}
func main() {
// 1. 监听
address := "127.0.0.1:8080"
lis, err := net.Listen("tcp", address)
if err != nil {
fmt.Println("监听异常 ", err)
return
}
fmt.Println("监听成功")
// 2. 实例化rpc
s := grpc.NewServer()
// 3. 在gRPC上注册微服务
// 第一个类型是服务,第二个类型是接口的变量
pb.RegisterUserInfoServiceServer(s, &u)
// 4. 启动gRPC服务端
_ = s.Serve(lis)
}
package main
import (
"context"
"fmt"
pb "github.com/pro911/godemo/grpc01/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func main() {
//1.创建与gRpc服务端的连接 //grpc.WithTransportCredentials(insecure.NewCredentials())建立无认证的连接
conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
fmt.Println("连接异常", err)
}
defer conn.Close()
// 2. 实例化gRPC客户端
client := pb.NewUserInfoServiceClient(conn)
// 3. 组装参数
req := new(pb.UserRequest)
req.Name = "zs"
// 4. 调用接口
resp, err := client.GetUserInfo(context.Background(), req)
if err != nil {
fmt.Println("响应异常", err)
}
fmt.Println("响应结果", resp)
}
module github.com/pro911/godemo/grpc01
go 1.17
require (
github.com/golang/protobuf v1.5.2 // indirect
golang.org/x/net v0.0.0-20201021035429-f5854403a974 // indirect
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 // indirect
golang.org/x/text v0.3.3 // indirect
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect
google.golang.org/grpc v1.47.0 // indirect
google.golang.org/protobuf v1.27.1 // indirect
)