您的位置 首页 golang

Protobuf+gRpc Go语言微服务组件搭建


必备下载

由于protobuf设定的是定义中间文件并转为每个语言的文件,所以必须装一个protoc的编译器
https://github.com/protocolbuffers/protobuf/releases

而go则再需要一个插件
https://github.com/golang/protobuf/tree/master/protoc-gen-go

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

配置

protoc 将解压后的文件配置到path中

项目结构

Protobuf+gRpc Go语言微服务组件搭建
image.png

Go的项目结构大概分为bin、pkg、src三个,bin是编译后可执行的文件,pkg是一些依赖包存放的地方,src就是编写的源码

此外,需要在src下新建一个go.mod文件,有点类似Java的pom.xml,做一些依赖的配置

module demogo 1.13require (    github.com/gin-gonic/gin v1.6.2    github.com/golang/protobuf v1.4.2    google.golang.org/grpc v1.29.1    google.golang.org/protobuf v1.23.0)

然后在src下新建一个文件夹存放proto文件

Protobuf+gRpc Go语言微服务组件搭建
image.png

Protobuf是一个定义通信格式的协议,不同的进程(Java,C++,Go whatever)只要遵循这个协议都可以进行序列化和反序列化,而且性能很高。

syntax = "proto3";package proto;message HelloRequest{  string name = 1;}message HelloResponse{  string message = 1;}service Hello{  rpc Say (HelloRequest) returns (HelloResponse) {};}

编写完成之后,程序依然无法识别这个rpc接口,它不像maven一样,做一个接口包然后共享出去,用户方通过pom文件的引入,就能看到接口定义进而调用。
它需要执行一个编译,使用go generation进行生成中间文件。
到proto的目录下,执行这个,使用grpc的插件生成中间文件,这样就能得到接口定义的go文件。

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

服务端代码

package mainimport (    "context"    my "demo/myproto"    "google.golang.org/grpc"    "google.golang.org/grpc/reflection"    "log"    "net")type server struct{}const (    port = ":8081")func (s *server) Say(ctx context.Context, in *my.HelloRequest) (*my.HelloResponse, error) {    log.Printf("Received: %s", in.Name)    return &my.HelloResponse{Message: "hello"}, nil}func listenAndService(){    lis,err := net.Listen("tcp",port)    if err != nil{        log.Fatalf("failed to listen,%v",err)    }    s := grpc.NewServer()    my.RegisterHelloServer(s, &server{})    //注册服务    reflection.Register(s)    log.Print("the rpc server is started upn")    if err := s.Serve(lis); err != nil {        log.Fatalf("failed to serve %v",err)    }}func main(){    listenAndService()}

首先注意的第一点,跨go文件调用,定义的方法名首字母必须大写,如果是小写则不能被外部go文件调用,类似于private。
其次就是引包路径(匪夷所思,伞兵设计),是从你GOPATH开始,demo/myproto,中间的src哪去了不知道。
还有就是,不知道为什么定义个server的结构体。

客户端代码

package mainimport (    "context"    rpc "demo/myproto"    "google.golang.org/grpc"    "log")const PORT = ":8081"func main(){    conn,err := grpc.Dial(PORT,grpc.WithInsecure())    if err != nil {        log.Fatalf("get an error : %vn", err)    }    defer conn.Close()    client := rpc.NewHelloClient(conn)    resp,err := client.Say(context.Background(),&rpc.HelloRequest{        Name: "this is client",    })    if err != nil {        log.Fatalf("invoke error n")    }    log.Printf("resp : %sn",resp.GetMessage())}

实验截图

Protobuf+gRpc Go语言微服务组件搭建
image.png
Protobuf+gRpc Go语言微服务组件搭建
image.png

文章来源:智云一二三科技

文章标题:Protobuf+gRpc Go语言微服务组件搭建

文章地址:https://www.zhihuclub.com/855.shtml

关于作者: 智云科技

热门文章

评论已关闭

33条评论

  1. Raloxifene can be prescribed by primary care clinicians, nurse practitioners, physician assistants, OB GYNS, and endocrinologists For both duration and cumulativedose, the highest relative risk was 3

  2. any number of variants in rs35599367 and rs776746 and the reference category of 0 variant alleles

  3. Rapid response and slow recovery of the H3K4me3 epigenomic marker in the liver after light mediated phase advances of the circadian clock

  4. Treatment with either an angiogenesis or an aromatase inhibitor by itself certainly has merit Is RAD 140 stronger than testosterone

  5. Downsides If you are between the ages of 18 and 60, take no other medication or have no other medical conditions, side effects you are more likely to experience include A headache, nausea, dyspepsia, joint or back pain, nasal and sinus congestion, or a rash

  6. Other women have very regular cycles; their periods always seem to come at predictable intervals

  7. Table 10 Laboratory Abnormalities Occurring in 10 of Patients in MONALEESA 3 Laboratory Parameters Fulvestrant plus Ribociclib N 483 Fulvestrant plus Placebo N 241 All Grades Grade 3 Grade 4 All Grades Grade 3 Grade 4 Hematology Leukocyte count decreased 95 25 26 0 Neutrophil count decreased 92 46 7 21 0 Hemoglobin decreased 60 4 0 35 3 0 Lymphocyte count decreased 69 14 1 35 4 Platelet count decreased 33 1 11 0 0 Chemistry Creatinine increased 65 33 0 Gamma glutamyl transferase increased 52 6 1 49 8 2 Aspartate aminotransferase increased 49 5 2 43 3 0 Alanine aminotransferase increased 44 8 3 37 2 0 Glucose serum decreased 23 0 0 18 0 0 Phosphorous decreased 18 5 0 8 0 Albumin decreased 12 0 0 8 0 0 It is estimated that 80 of the world population uses medicinal plants in the treatment of diseases 1

  8. It is the most natural, best performing, pleasurable product of its type on the market Two types of kit are available regular for infrequent and lightweight smokers and extra strong for regular or heavyweight users

  9. AlexaFluor 488 conjugated goat anti rabbit 1 500, Thermo Fisher Scientific; RRID AB_2576217 was used as secondary antibody after a further overnight incubation at 4 C

  10. Clenbutrol crazy bulk is a popular steroid alternative that bodybuilders use to retain their lean muscle, encourage fat loss, and improve endurance and energy 8 of patients in the control group; the relative reduction of AKI was 39

  11. If one line appears on that stick, you get a negative result aka a BFN Big Fat Negative For example, in one study, five of twelve patients 42 with morbilliform eruptions who had negative patch test results subsequently exhibited positive skin prick or intradermal tests to the suspected drugs

  12. Dynamic transmission modeling a report of the ISPOR SMDM Modeling Good Research Practices Task Force 5

  13. It is also effective against respiratory infections such as kennel cough, pneumonia, and bronchitis paroxetine, fluoxetine, quinidine, cinacalcet or bupropion should whenever possible be avoided during Tamoxifen Sopharma treatment

  14. Some studies suggest that some level of hearing impairment occurs in 65 to 70 of people exposed to a total dose of cisplatin greater than 200 mg m

  15. Now the kids are back in school, and colds have threatened to crop up again After 24 hr, 100 Ојl of viral particles suspension were added to each well

  16. Acne, oily skin Erectile dysfunction Low libido Lethargy Gynecomastia man boobs Aggression and bitchiness Depression Water retention High blood pressure Enlarged prostate Shrunken testicles Sugar cravings

网站地图