• linux下golang gRPC配置详解


    1.安装gRPC运行环境

    go get google.golang.org/grpc
    

    这里的grpc通俗来说就说用在代码里的一个类库,后面的例子可以看到。比较坑的是这里可能需要翻墙.....

    2.安装protoc

    这里需要安装proto buffer的编译器。首先在官网下载,如c++版本的protobuf-cpp-3.4.1.tar.gz,解压后进行编译:

    ./configure         
    make && make install
    

    3.安装protoc-gen-go

    go get -a github.com/golang/protobuf/protoc-gen-go
    

    4.编写proto文件

    基于protobuf的跨语言的特性,不难想到它自己实现了一套数据类型。这里有一个简单的例子

    //testHello.proto
    syntax = "proto3";
    
    package protos;
    
    // The service definition.
    service Devops {
        // 定义服务
        rpc SayHello (HelloRequest) returns (Response) {}
    }
    
    // The request message containing the user's name.
    message HelloRequest {
        string name = 1;
    }
    
    // The response message
    message HelloReply {
        string message = 1;
    }
    
    message Response {
        enum StatusCode {
            UNDEFINED = 0;
            SUCCESS = 200;
            FAILURE = 500;
        }
        StatusCode status = 1;
        HelloReply msg = 2;
    }
    

    然后在终端自动生成pb.go:

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

    5.编写服务端

    package main
    
    const (
    	port = ":50051"
    )
    
    type myserver struct{}
    
    //这里myserver实现了SayHello
    func (s *myserver) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.Response, error) {
    	fmt.Print("receive " + in.Name)
    	return &pb.Response{
    		Status:pb.Response_SUCCESS,
    		Msg:&pb.HelloReply{Message:"receive " + in.Name},
    	}, nil
    }
    
    func main() {
    	//绑定端口
    	lis, err := net.Listen("tcp", port)
    	if err != nil{
    		log.Fatal("fail to listen")
    	}
    
    	s := grpc.NewServer()
    	pb.RegisterDevopsServer(s, &myserver{})
    	s.Serve(lis)
    }
    

    6.编写客户端

    package main
    
    const (
    	address = "localhost:50051"
    )
    
    func main()  {
       //grpc.WithInsecure()指定后才不会报错
    	conn, err := grpc.Dial(address, grpc.WithInsecure())
    
    	if err != nil{
    		log.Fatal("error....", err)
    	}
    	c := pb.NewDevopsClient(conn)
    	res, _ := c.SayHello(context.Background(), &pb.HelloRequest{"eeee"})
    
    	fmt.Print(res)
    }
    

    WithInsecure returns a DialOption which disables transport security for this ClientConn.
    Note that transport security is required unless WithInsecure is set.

    WithInsecure返回一个DialOption,它在传输过程中不保证安全。除非设置WithInsecure,否则grpc.Dial必须指定安全选项。

    参考:

    1.https://github.com/google/protobuf/releases
    2.http://www.cnblogs.com/YaoDD/p/5504881.html

  • 相关阅读:
    margin+absolute布局:右栏固定主内容自适应 demo
    localForage——轻松实现 Web 离线存储
    迷你MVVM框架 avalonjs 1.2.6发布
    收起.NET程序的dll来
    从锅炉工到AI专家 ---- 系列教程
    DevExpress中实现GridControl的分页功能
    树莓派 ---- 个人总结
    树莓派安装内网穿透版花生壳服务
    winform 多线程中ShowDialog()模式窗口无效的解决办法
    局域网匿名访问共享文件
  • 原文地址:https://www.cnblogs.com/xiaodeshan/p/7794874.html
Copyright © 2020-2023  润新知