SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
Build microserviceBuild microservice
with gRPC in Golangwith gRPC in Golang
David Chou
We are UmboWe are Umbo
Computer VisionComputer Vision
We buildWe build
autonomous videoautonomous video
security systemsecurity system
CyberlinkCyberlink
TrendMicroTrendMicro
Umbo CVUmbo CV
Google I/O ExtendGoogle I/O Extend
Golang TaipeiGolang Taipei
  
A high performance, open source, general purpose
standards-based, feature-rich RPC framework.
O(10^10) RPCs per second at Google
gRPC: MotivationgRPC: Motivation
Google has its internal RPC called Stubby
All applications and systems built using RPCs
Over 10^10 RPCs per second
Tightly couple with internal infrastructure
Not suitable for open source community
gRPC: StatusgRPC: Status
A high performance, universal RPC framework
Google open sourced it in Feb 2015
Being 1.0 in Aug 2016
Latest version: v1.3.2
Already been adpoted in
CoreOS, Netflix, Square, Cisco, Juniper
gRPC: FeaturesgRPC: Features
Bi-directional streaming over HTTP/2
Support multi-language, multi-platform
Simple service definition framework
Bi-directional streaming over HTTP/2Bi-directional streaming over HTTP/2
Single TCP connection for each client-server pair
Support bi-directional streaming
Support multi-language,Support multi-language,
multi-platformmulti-platform
Use protoc as the code generator
Native implementations in C/C++, Java, and Go
C stack wrapped by C#, Node, ObjC, Python, Ruby, PHP
Platforms supported: Linux, MacOS, Windows, Android, iOS
Currently, no browser side support. #8682
gRPC gateway
gRPC-web
Simple service definition frameworkSimple service definition framework
Use Protocol Buffer IDL
Service definition
Generate server and client stub code
Message definition
Binary format
Much better performace than json
syntax = "proto3";
package pb;
message EchoMessage {
string msg = 1;
}
service EchoService {
rpc Echo(EchoMessage) returns (EchoMessage);
}
Protobuf IDL: EchoServiceProtobuf IDL: EchoService
BenchmarkToJSON_1000_Director-2 500 2512808 ns/op 560427 B/op 9682 allocs/op
BenchmarkToPB_1000_Director-2 2000 1338410 ns/op 196743 B/op 3052 allocs/op
BenchmarkToJSONUnmarshal_1000_Director-4 1000 1279297 ns/op 403746 B/op 5144 allocs/op
BenchmarkToPBUnmarshal_1000_Director-4 3000 489585 ns/op 202256 B/op 5522 allocs/op
Json vs Protobuf performanceJson vs Protobuf performance
Ref: Dgraph: JSON vs. Binary clients
Marshalling: 2x faster, 65% less memory
Unmarshalling: 2.6x faster, 50% less memory
Example: DemoServiceExample: DemoService
gRPC Service DefinitiongRPC Service Definition
message Demo {
string value = 1;
}
service DemoService {
rpc SimpleRPC(Demo) returns (Demo);
rpc ServerStream(Demo) returns (stream Demo);
rpc ClientStream(stream Demo) returns (Demo);
rpc Bidirectional(stream Demo) returns (stream Demo);
}
gRPC Service DefinitiongRPC Service Definition
gRPC supprots 4 kinds of service methods
Unary RPC
Server streaming RPC
Client streaming RPC
Bidirectional RPC
Generate client and server codeGenerate client and server code
Run protoc to generate client/server interfaces
$ protoc --go_out=plugins=grpc:. demo.proto
protoc will generate demo.pb.go
Install relevant tools
demo.pb.godemo.pb.go
type Demo struct {
Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"`
}
// Client API for DemoService service
type DemoServiceClient interface {
SimpleRPC(ctx context.Context, in *Demo, opts ...grpc.CallOption) (*Demo, error)
ServerStream(ctx context.Context, in *Demo, opts ...grpc.CallOption) (DemoService_ServerStreamClient,
ClientStream(ctx context.Context, opts ...grpc.CallOption) (DemoService_ClientStreamClient, error)
Bidirectional(ctx context.Context, opts ...grpc.CallOption) (DemoService_BidirectionalClient, error)
}
// Implementation of DemoService client
type demoServiceClient struct {
cc *grpc.ClientConn
}
func NewDemoServiceClient(cc *grpc.ClientConn) DemoServiceClient {
...
}
// Server API for DemoService service
type DemoServiceServer interface {
SimpleRPC(context.Context, *Demo) (*Demo, error)
ServerStream(*Demo, DemoService_ServerStreamServer) error
ClientStream(DemoService_ClientStreamServer) error
Bidirectional(DemoService_BidirectionalServer) error
}
Go ServerGo Server
type server struct{}
func (this *server) SimpleRPC(c context.Context, msg *Demo) (*Demo, error) {
msg.Value = "Hello" + msg.Value
return msg, nil
}
func (this *server) ServerStream(msg *Demo, stream DemoService_ServerStreamServer) error {
for i := 0; i < 10; i++ {
err := stream.Send(&Demo{value: "Hello"})
if err != nil {
fmt.Printf("err: %sn", err.Error())
}
time.Sleep(100 * time.Millisecond)
}
return nil
}
func main() {
lis, err := net.Listen("tcp", "localhost:12345")
if err != nil {
log.Fatalf("Failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
RegisterDemoServiceServer(grpcServer, &server{})
grpcServer.Serve(lis)
}
Go Client: SimpleRPCGo Client: SimpleRPC
func main() {
grpcAddr := "localhost:12345"
conn, err := grpc.Dial(grpcAddr)
if err != nil {
log.Fatalf("Dial(%s) = %v", grpcAddr, err)
}
defer conn.Close()
client := NewDemoServiceClient(conn)
msg := &Demo{value: "World"}
reply, err := client.SimpleRPC(context.Background(), msg)
if err != nil {
log.Fatalf("SimpleRPC(%#v) failed with %v", msg, err)
}
println("received message " + reply.Value)
}
Go Client: ServerStreamGo Client: ServerStream
func main() {
grpcAddr := "localhost:12345"
conn, err := grpc.Dial(grpcAddr)
if err != nil {
log.Fatalf("Dial(%s) = %v", grpcAddr, err)
}
defer conn.Close()
client := NewDemoServiceClient(conn)
stream, err := client.ServerStream(context.TODO(), &Demo{
Value: "Hello",
})
for {
msg, err := stream.Recv()
if err == io.EOF {
break
}
fmt.Printf("%+vn", msg)
}
}
Let's go deeperLet's go deeper
gRPC build-in authenticationgRPC build-in authentication
Two types of Credentials objects
Channel credentials
Call credentials
Channel credentialsChannel credentials
Credentials are attached to a Channel
Ex: SSL credentials
tls := credentials.NewClientTLSFromCert(nil, "")
conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(tls))
creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
server := grpc.NewServer(grpc.Creds(creds))
server.Serve()
TLS on server side
TLS on client side
Call credentialsCall credentials
Credentials are attached to each RPC call
Token based authentication, ex: OAuth, JWT
func unaryInterceptor(ctx context.Context, req interface{}
if err := authorize(ctx); err != nil {
return err
}
return handler(ctx, req)
}
func authorize(ctx context.Context) error {
if md, ok := metadata.FromContext(ctx); ok {
if checkJWT(md["jwt"][0]) {
return nil
}
return AccessDeniedErr
}
return EmptyMetadataErr
}
grpc.NewServer(grpc.UnaryInterceptor(unaryInterceptor))
TLS on server side
type JWTCreds struct {
Token string
}
func (c *JWTCreds) GetRequestMetadata(context.Context, ..
return map[string]string{
"jwt": c.Token,
}, nil
}
grpc.Dial(target, grpc.WithPerRPCCredentials(&JWTCreds{
Token: "test-jwt-token",
}))
TLS on client side
Ref: grpc-go #106
gRPC load balancegRPC load balance
Approaches to Load Balancing
Server-side LB
Client-side LB
Load Balancing in gRPCLoad Balancing in gRPC
#gRPC load balancing proposal
Any Question?Any Question?

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to gRPC
Introduction to gRPCIntroduction to gRPC
Introduction to gRPCPrakash Divy
 
gRPC Design and Implementation
gRPC Design and ImplementationgRPC Design and Implementation
gRPC Design and ImplementationVarun Talwar
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Advanced java
Advanced java Advanced java
Advanced java NA
 
Monitoring microservices with Prometheus
Monitoring microservices with PrometheusMonitoring microservices with Prometheus
Monitoring microservices with PrometheusTobias Schmidt
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_scriptVijay Kalyan
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxNir Elbaz
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker PresentationKyle Dorman
 
Server-Sent Events in Action
Server-Sent Events in ActionServer-Sent Events in Action
Server-Sent Events in ActionAndrei Rusu
 
Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webserviceDong Ngoc
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
 
Simple Object Access Protocol
Simple Object Access ProtocolSimple Object Access Protocol
Simple Object Access ProtocolSaatviga Sudhahar
 

Was ist angesagt? (20)

Introduction to gRPC
Introduction to gRPCIntroduction to gRPC
Introduction to gRPC
 
gRPC Design and Implementation
gRPC Design and ImplementationgRPC Design and Implementation
gRPC Design and Implementation
 
Express JS
Express JSExpress JS
Express JS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Servlets
ServletsServlets
Servlets
 
SOAP-based Web Services
SOAP-based Web ServicesSOAP-based Web Services
SOAP-based Web Services
 
Advanced java
Advanced java Advanced java
Advanced java
 
Monitoring microservices with Prometheus
Monitoring microservices with PrometheusMonitoring microservices with Prometheus
Monitoring microservices with Prometheus
 
gRPC Overview
gRPC OverviewgRPC Overview
gRPC Overview
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker Presentation
 
Server-Sent Events in Action
Server-Sent Events in ActionServer-Sent Events in Action
Server-Sent Events in Action
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
 
Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webservice
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
Simple Object Access Protocol
Simple Object Access ProtocolSimple Object Access Protocol
Simple Object Access Protocol
 
gRPC
gRPC gRPC
gRPC
 

Ähnlich wie Build microservice with gRPC in golang

Microservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPCMicroservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPCWSO2
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays
 
MessagePack Rakuten Technology Conference 2010
MessagePack Rakuten Technology Conference 2010MessagePack Rakuten Technology Conference 2010
MessagePack Rakuten Technology Conference 2010Sadayuki Furuhashi
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPCDocker, Inc.
 
REST in Peace. Long live gRPC! @ Codineers
REST in Peace. Long live gRPC! @ CodineersREST in Peace. Long live gRPC! @ Codineers
REST in Peace. Long live gRPC! @ CodineersQAware GmbH
 
Microservices summit talk 1/31
Microservices summit talk   1/31Microservices summit talk   1/31
Microservices summit talk 1/31Varun Talwar
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCTim Burks
 
Usable APIs at Scale
Usable APIs at ScaleUsable APIs at Scale
Usable APIs at ScaleTim Burks
 
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}Md. Sadhan Sarker
 
Implementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCImplementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCTim Burks
 
gRPC 프레임워크를 만들며 알아보는 파이썬 - 파이콘2020
gRPC 프레임워크를 만들며 알아보는 파이썬  - 파이콘2020gRPC 프레임워크를 만들며 알아보는 파이썬  - 파이콘2020
gRPC 프레임워크를 만들며 알아보는 파이썬 - 파이콘2020재현 신
 
Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022QAware GmbH
 
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, GoogleBringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, GoogleAmbassador Labs
 
gRPC or Rest, why not both?
gRPC or Rest, why not both?gRPC or Rest, why not both?
gRPC or Rest, why not both?Mohammad Murad
 
CRUD Operation With Dgraph
CRUD Operation With DgraphCRUD Operation With Dgraph
CRUD Operation With DgraphKnoldus Inc.
 
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John FallowsEnd-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John FallowsHostedbyConfluent
 
UA Mobile 2012 (English)
UA Mobile 2012 (English)UA Mobile 2012 (English)
UA Mobile 2012 (English)dmalykhanov
 
Running gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on KubernetesRunning gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on KubernetesSungwon Lee
 

Ähnlich wie Build microservice with gRPC in golang (20)

Microservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPCMicroservices Communication Patterns with gRPC
Microservices Communication Patterns with gRPC
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
 
MessagePack Rakuten Technology Conference 2010
MessagePack Rakuten Technology Conference 2010MessagePack Rakuten Technology Conference 2010
MessagePack Rakuten Technology Conference 2010
 
Apa itu gRPC_.pptx
Apa itu gRPC_.pptxApa itu gRPC_.pptx
Apa itu gRPC_.pptx
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPC
 
REST in Peace. Long live gRPC! @ Codineers
REST in Peace. Long live gRPC! @ CodineersREST in Peace. Long live gRPC! @ Codineers
REST in Peace. Long live gRPC! @ Codineers
 
Microservices summit talk 1/31
Microservices summit talk   1/31Microservices summit talk   1/31
Microservices summit talk 1/31
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPC
 
Usable APIs at Scale
Usable APIs at ScaleUsable APIs at Scale
Usable APIs at Scale
 
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
Up and Running with gRPC & Cloud Career [GDG-Cloud-Dhaka-IO/2022}
 
Implementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCImplementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPC
 
gRPC 프레임워크를 만들며 알아보는 파이썬 - 파이콘2020
gRPC 프레임워크를 만들며 알아보는 파이썬  - 파이콘2020gRPC 프레임워크를 만들며 알아보는 파이썬  - 파이콘2020
gRPC 프레임워크를 만들며 알아보는 파이썬 - 파이콘2020
 
Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022Cloud native IPC for Microservices Workshop @ Containerdays 2022
Cloud native IPC for Microservices Workshop @ Containerdays 2022
 
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, GoogleBringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
 
gRPC or Rest, why not both?
gRPC or Rest, why not both?gRPC or Rest, why not both?
gRPC or Rest, why not both?
 
CRUD Operation With Dgraph
CRUD Operation With DgraphCRUD Operation With Dgraph
CRUD Operation With Dgraph
 
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John FallowsEnd-to-end Streaming Between gRPC Services Via Kafka with John Fallows
End-to-end Streaming Between gRPC Services Via Kafka with John Fallows
 
UA Mobile 2012 (English)
UA Mobile 2012 (English)UA Mobile 2012 (English)
UA Mobile 2012 (English)
 
gRPC - RPC rebirth?
gRPC - RPC rebirth?gRPC - RPC rebirth?
gRPC - RPC rebirth?
 
Running gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on KubernetesRunning gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on Kubernetes
 

Kürzlich hochgeladen

MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 

Kürzlich hochgeladen (20)

MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 

Build microservice with gRPC in golang

  • 1. Build microserviceBuild microservice with gRPC in Golangwith gRPC in Golang David Chou
  • 2. We are UmboWe are Umbo Computer VisionComputer Vision We buildWe build autonomous videoautonomous video security systemsecurity system
  • 3. CyberlinkCyberlink TrendMicroTrendMicro Umbo CVUmbo CV Google I/O ExtendGoogle I/O Extend Golang TaipeiGolang Taipei   
  • 4. A high performance, open source, general purpose standards-based, feature-rich RPC framework.
  • 5. O(10^10) RPCs per second at Google
  • 6. gRPC: MotivationgRPC: Motivation Google has its internal RPC called Stubby All applications and systems built using RPCs Over 10^10 RPCs per second Tightly couple with internal infrastructure Not suitable for open source community
  • 7. gRPC: StatusgRPC: Status A high performance, universal RPC framework Google open sourced it in Feb 2015 Being 1.0 in Aug 2016 Latest version: v1.3.2 Already been adpoted in CoreOS, Netflix, Square, Cisco, Juniper
  • 8. gRPC: FeaturesgRPC: Features Bi-directional streaming over HTTP/2 Support multi-language, multi-platform Simple service definition framework
  • 9. Bi-directional streaming over HTTP/2Bi-directional streaming over HTTP/2 Single TCP connection for each client-server pair Support bi-directional streaming
  • 10. Support multi-language,Support multi-language, multi-platformmulti-platform Use protoc as the code generator Native implementations in C/C++, Java, and Go C stack wrapped by C#, Node, ObjC, Python, Ruby, PHP Platforms supported: Linux, MacOS, Windows, Android, iOS Currently, no browser side support. #8682 gRPC gateway gRPC-web
  • 11. Simple service definition frameworkSimple service definition framework Use Protocol Buffer IDL Service definition Generate server and client stub code Message definition Binary format Much better performace than json
  • 12. syntax = "proto3"; package pb; message EchoMessage { string msg = 1; } service EchoService { rpc Echo(EchoMessage) returns (EchoMessage); } Protobuf IDL: EchoServiceProtobuf IDL: EchoService
  • 13. BenchmarkToJSON_1000_Director-2 500 2512808 ns/op 560427 B/op 9682 allocs/op BenchmarkToPB_1000_Director-2 2000 1338410 ns/op 196743 B/op 3052 allocs/op BenchmarkToJSONUnmarshal_1000_Director-4 1000 1279297 ns/op 403746 B/op 5144 allocs/op BenchmarkToPBUnmarshal_1000_Director-4 3000 489585 ns/op 202256 B/op 5522 allocs/op Json vs Protobuf performanceJson vs Protobuf performance Ref: Dgraph: JSON vs. Binary clients Marshalling: 2x faster, 65% less memory Unmarshalling: 2.6x faster, 50% less memory
  • 14.
  • 16. gRPC Service DefinitiongRPC Service Definition message Demo { string value = 1; } service DemoService { rpc SimpleRPC(Demo) returns (Demo); rpc ServerStream(Demo) returns (stream Demo); rpc ClientStream(stream Demo) returns (Demo); rpc Bidirectional(stream Demo) returns (stream Demo); }
  • 17. gRPC Service DefinitiongRPC Service Definition gRPC supprots 4 kinds of service methods Unary RPC Server streaming RPC Client streaming RPC Bidirectional RPC
  • 18. Generate client and server codeGenerate client and server code Run protoc to generate client/server interfaces $ protoc --go_out=plugins=grpc:. demo.proto protoc will generate demo.pb.go Install relevant tools
  • 19. demo.pb.godemo.pb.go type Demo struct { Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"` } // Client API for DemoService service type DemoServiceClient interface { SimpleRPC(ctx context.Context, in *Demo, opts ...grpc.CallOption) (*Demo, error) ServerStream(ctx context.Context, in *Demo, opts ...grpc.CallOption) (DemoService_ServerStreamClient, ClientStream(ctx context.Context, opts ...grpc.CallOption) (DemoService_ClientStreamClient, error) Bidirectional(ctx context.Context, opts ...grpc.CallOption) (DemoService_BidirectionalClient, error) } // Implementation of DemoService client type demoServiceClient struct { cc *grpc.ClientConn } func NewDemoServiceClient(cc *grpc.ClientConn) DemoServiceClient { ... } // Server API for DemoService service type DemoServiceServer interface { SimpleRPC(context.Context, *Demo) (*Demo, error) ServerStream(*Demo, DemoService_ServerStreamServer) error ClientStream(DemoService_ClientStreamServer) error Bidirectional(DemoService_BidirectionalServer) error }
  • 20. Go ServerGo Server type server struct{} func (this *server) SimpleRPC(c context.Context, msg *Demo) (*Demo, error) { msg.Value = "Hello" + msg.Value return msg, nil } func (this *server) ServerStream(msg *Demo, stream DemoService_ServerStreamServer) error { for i := 0; i < 10; i++ { err := stream.Send(&Demo{value: "Hello"}) if err != nil { fmt.Printf("err: %sn", err.Error()) } time.Sleep(100 * time.Millisecond) } return nil } func main() { lis, err := net.Listen("tcp", "localhost:12345") if err != nil { log.Fatalf("Failed to listen: %v", err) } grpcServer := grpc.NewServer() RegisterDemoServiceServer(grpcServer, &server{}) grpcServer.Serve(lis) }
  • 21. Go Client: SimpleRPCGo Client: SimpleRPC func main() { grpcAddr := "localhost:12345" conn, err := grpc.Dial(grpcAddr) if err != nil { log.Fatalf("Dial(%s) = %v", grpcAddr, err) } defer conn.Close() client := NewDemoServiceClient(conn) msg := &Demo{value: "World"} reply, err := client.SimpleRPC(context.Background(), msg) if err != nil { log.Fatalf("SimpleRPC(%#v) failed with %v", msg, err) } println("received message " + reply.Value) }
  • 22. Go Client: ServerStreamGo Client: ServerStream func main() { grpcAddr := "localhost:12345" conn, err := grpc.Dial(grpcAddr) if err != nil { log.Fatalf("Dial(%s) = %v", grpcAddr, err) } defer conn.Close() client := NewDemoServiceClient(conn) stream, err := client.ServerStream(context.TODO(), &Demo{ Value: "Hello", }) for { msg, err := stream.Recv() if err == io.EOF { break } fmt.Printf("%+vn", msg) } }
  • 23. Let's go deeperLet's go deeper
  • 24. gRPC build-in authenticationgRPC build-in authentication Two types of Credentials objects Channel credentials Call credentials
  • 25. Channel credentialsChannel credentials Credentials are attached to a Channel Ex: SSL credentials tls := credentials.NewClientTLSFromCert(nil, "") conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(tls)) creds, err := credentials.NewServerTLSFromFile(certFile, keyFile) server := grpc.NewServer(grpc.Creds(creds)) server.Serve() TLS on server side TLS on client side
  • 26. Call credentialsCall credentials Credentials are attached to each RPC call Token based authentication, ex: OAuth, JWT
  • 27. func unaryInterceptor(ctx context.Context, req interface{} if err := authorize(ctx); err != nil { return err } return handler(ctx, req) } func authorize(ctx context.Context) error { if md, ok := metadata.FromContext(ctx); ok { if checkJWT(md["jwt"][0]) { return nil } return AccessDeniedErr } return EmptyMetadataErr } grpc.NewServer(grpc.UnaryInterceptor(unaryInterceptor)) TLS on server side type JWTCreds struct { Token string } func (c *JWTCreds) GetRequestMetadata(context.Context, .. return map[string]string{ "jwt": c.Token, }, nil } grpc.Dial(target, grpc.WithPerRPCCredentials(&JWTCreds{ Token: "test-jwt-token", })) TLS on client side Ref: grpc-go #106
  • 28. gRPC load balancegRPC load balance Approaches to Load Balancing Server-side LB Client-side LB
  • 29.
  • 30.
  • 31. Load Balancing in gRPCLoad Balancing in gRPC #gRPC load balancing proposal