Upgrade to Pro — share decks privately, control downloads, hide ads and more …

イメージで理解するgRPC

 イメージで理解するgRPC

Daiki Nojiri

May 23, 2020
Tweet

More Decks by Daiki Nojiri

Other Decks in Programming

Transcript

  1. const res = axios.get("/api/v1/users/1") js req := FindRequest({ID: 1}) res,

    err = user.Find(req) go 3&45 31$ ͜Μͳ࢖͍ํ͕Ͱ͖·͢
  2. QSPUPϑΝΠϧͷྫ service User { rpc Find(FindRequest) returns (FindResponse) {} }

    message FindRequest { int32 id = 1; } message FindResponse { string name = 1; } user_service.proto
  3. QSPUPϑΝΠϧͷྫ user_service.proto ϦΫΤετͷܗࣜ Ϩεϙϯεͷܗࣜ service User { rpc Find(FindRequest) returns

    (FindResponse) {} } message FindRequest { int32 id = 1; } message FindResponse { string name = 1; }
  4. service User { rpc Find(FindRequest) returns (FindResponse) {} } message

    FindRequest { int32 id = 1; } message FindResponse { string name = 1; } QSPUPϑΝΠϧͷྫ user_service.proto ˢϝιουͷఆٛ
  5. ॏཁͳ෦෼͚ͩϐοΫΞοϓ type UserServer interface { Find( context.Context, *FindRequest ) (*FindResponse,

    error) } user_service.pb.go  αʔόଆͷΠϯλʔϑΣʔε αʔόଆ͸͜Εʹ߹ΘͤͯϝιουΛ࣮૷͢Δ
  6. ॏཁͳ෦෼͚ͩϐοΫΞοϓ type UserClient interface { Find( ctx context.Context, in *FindRequest,

    opts ...grpc.CallOption ) (*FindResponse, error) }  ΫϥΠΞϯτଆͷΠϯλʔϑΣʔε ΫϥΠΞϯτଆ͸͜Εʹ߹ΘͤͯϝιουΛ࢖͏ user_service.pb.go
  7. ॏཁͳ෦෼͚ͩϐοΫΞοϓ func (c *userClient) Find( ctx context.Context, in *FindRequest, opts

    ...grpc.CallOption ) (*FindResponse, error) { out := new(FindResponse) err := c.cc.Invoke( ctx, "/user_service.User/Find", in, out, opts... ) if err != nil { return nil, err } return out, nil }  ΫϥΠΞϯτଆͷϝιου ΫϥΠΞϯτଆ͕ݺͼग़͢ϝιου͸࣮૷ࡁΈ user_service.pb.go
  8. αʔόଆͷ࢖͍ํ ؆ུ൛ import pb "path/to/pb.go" type server struct{} func (s

    *server) Find( ctx context.Context, in *pb.FindRequest ) (*pb.FindResponse, error) { user := db.Find(&user) out := &pb.FindResponse{name: user.name} return out, nil } s := grpc.NewServer() pb.RegisterUserServer(s, &server{}) s.Serve(lis) server/main.go
  9. import pb "path/to/pb.go" type server struct{} func (s *server) Find(

    ctx context.Context, in *pb.FindRequest ) (*pb.FindResponse, error) { user := db.Find(&user) out := &pb.FindResponse{name: user.name} return out, nil } s := grpc.NewServer() pb.RegisterUserServer(s, &server{}) s.Serve(lis) αʔόଆͷ࢖͍ํ ؆ུ൛ server/main.go %#͔Β஋Λ औಘͯ͠ฦ͢ αʔόͷ্ཱͪ͛
  10. ΫϥΠΞϯτଆͷ࢖͍ํ ؆ུ൛ import pb "path/to/pb.go" c := pb.NewUserClient(conn) req :=

    &pb.FindRequest{ id: 1, } resp, err := c.Find(context.Background(), req) if err != nil { log.Fatal(err) } log.Println("Name: ", resp.name) // #=> Name: alice client/main.go
  11. ΫϥΠΞϯτଆͷ࢖͍ํ ؆ུ൛ import pb "path/to/pb.go" c := pb.NewUserClient(conn) req :=

    &pb.FindRequest{ Name: "alice", } resp, err := c.Find(context.Background(), req) if err != nil { log.Fatal(err) } log.Println("Name: ", resp.name) // #=> Name: alice client/main.go αʔόଆͷFind()ͷฦΓ஋