GoLang GRPC使用

服务器端文件结构主要是 proto 文件夹(主要是.proto文件),service文件夹,mian.go文件

定义GRPC  ptoto文件   注意:

                                            1. 头   syntax="proto3";  必要

                                            2. 包package的定义

                                            3. service 的定义

                                            4. rpc方法的定义 

                                            5.message 的定义

                                            6. repeated参数的定义(即集合参数)

syntax="proto3";
// 写实例,这里先这样定义package
option go_package = ".;protoes";

// 服务名称 和 rpc 方法   注意 请求必须加参数
service UserService{
    rpc GetUserUerById(Uid) returns (User);
    rpc GetUserListByDeptId(DeptParam) returns (UserList);
}
service OtherService{
    rpc GetSumBySumParam(SumParam) returns (SumResult);
}

message Uid{
// 用户Id
int32 userid=1;
}
message User{
// 用户id
int32 userid=1;
// 用户名
string username=2;
}

// 请求参数
message DeptParam{
    // 部门Id
   string dptName=1;
}

// 响应集合 列表  应该repeated 的用法
message UserList{
repeated User userlist=1;
}

message SumParam{
  repeated int32 arrNum=1;
}

message SumResult{
int32 sum=1;
}

 

写好上面的文件可以在命令行 cd 到当前文件所在的文件夹 通过

protoc --go_out=plugins=grpc:. mygrpc.proto

命令来生成pb文件

 

 

服务方法代码见下, 我这里写了两个服务

 注意 方法要和.proto里定义的方法名及参数一致

package services

import (
    "context"
    proto "mygrpc/proto"
)

type UserService struct {

}

// 根据用户名得到用户
func (this *UserService) GetUserUerById(ctx context.Context,Uid *proto.Uid) (*proto.User,error){
    user :=&proto.User{}
    user.Userid=1
    user.Username="zs"
    return user,nil
}

// 根据用户名得到所有的用户集合
func (this *UserService) GetUserListByDeptId(ctx context.Context,u *proto.DeptParam) (*proto.UserList,error){
    Alllist := &proto.UserList{}
    var userlist []*proto.User
    user :=&proto.User{}
    user.Userid=1
    user.Username="zs"
    userlist=append(userlist,user)
    Alllist.Userlist=userlist
    return Alllist,nil
}
package services

import (
    "context"
    protoes "mygrpc/proto"
)

// 其实服务
type OtherService struct {

}

// 这里 写了个计算求和
func (this *OtherService)  GetSumBySumParam(ctx context.Context,param *protoes.SumParam) (*protoes.SumResult,error){
    result :=&protoes.SumResult{}
    for _,v :=range param.ArrNum{
        result.Sum +=v
    }
    return result,nil
}

 

main()方法通用TCP挂载服务向外提搞服务

package main

import (
    "fmt"
    "google.golang.org/grpc"
    pb "mygrpc/proto"
    "mygrpc/services"
    "net"
)

func main(){
    // 开始服务器端监听
    listen,err :=net.Listen("tcp","localhost:8090")
    fmt.Println("listen :8090")
    if err!=nil{
        fmt.Println("listen err:",err)
        return
    }
    // 建立grpc服务实体
    grpcServer:=grpc.NewServer()
    // 注册 Grpc 相关服务   我这里写了两个服务
    pb.RegisterUserServiceServer(grpcServer,&services.UserService{})
    pb.RegisterOtherServiceServer(grpcServer,&services.OtherService{})
    // 将服务挂载到服务监听
    grpcServer.Serve(listen)
}

客户端代码   主要是引入服务端的pb.go文件

 

 

 然后在main()里面调用

package main

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

    protoes "grpcclient/protoes"
)

func main(){
    fmt.Println("客户端开始……")
    conn,err:=grpc.Dial(":8090",grpc.WithInsecure())
    if err!=nil{
        fmt.Println("creeate conn err:",err)
        return
    }
    defer conn.Close()
    // 建立User客户端
    userClient:=protoes.NewUserServiceClient(conn)
    // 调用  UserService  服务里面的  GetUserListByDeptId 方法
    uerlist,err:= userClient.GetUserListByDeptId(context.Background(),&protoes.DeptParam{DptName: "1"})
    if err!=nil{
        fmt.Println("调用Grpc服务GetUserListByDeptId出错:",err)
    }
    fmt.Println(uerlist)  // 打印 GetUserListByDeptId 结果
    param:= make([]int32,3)
    param[0]=1
    param[1]=1
    param[2]=1
    sumParam:= &protoes.SumParam{ArrNum:param}
    // 建立Other服务客户端
    otherClient :=protoes.NewOtherServiceClient(conn)
    // 调用GetAaddB  求合方法
    result,err:= otherClient.GetSumBySumParam(context.Background(),sumParam)
    if err!=nil{
        fmt.Println("调用Grpc服务GetAaddB出错:",err)
    }
    fmt.Println(result)
}

 

 

 

 

 

posted @   酒沉吟  阅读(271)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示