SlideShare a Scribd company logo
1 of 56
Xây dựng Go microservice
với Golang
cuong@techmaster.vn
Tải slide bit.ly/gomicro
Agenda
• Pattern phổ biến trong microservices
• GRPC Protobuf vs REST
• Go Micro / Service Discovery / Consul
• Request Response vs Pub Sub / Nat.io
Monolithic sang microservices
• Không chạy theo trào lưu
• Giải quyết vấn đề hiện tại (khó bảo trì, không bảo
mật code)
• Học hỏi kinh nghiệm của người đi trước
• Tận dụng mã nguồn mở
• Từ nhỏ đến lớn
Pattern, lựa chọn công nghệ cho
microservices thì quá nhiều
Availability
• Health Endpoint
Monitoring
• Queue based Load
Leveling
• Throttling
Data Management
• Cache Aside
• CQRS
• Event Sourcing
• Index Table
• Materialized View
• Sharding
• Static Content
• Valet Key
Messaging
• Competing
Consumers
• Pipes and Filter
• Priority Queue
• Queue – Load
Balancing
• Scheduler – Agent -
Supervisor
Tổng hợp từ tài liệu Microservice Design Pattern của Microsoft
Management
and Monitor
• Ambassador
• Anti Corruption Layer
• External Configuration
Store
• Gateway Aggregation
• Gateway Offloading
• Gateway Routing
• SideCar
• Strangler
Performance Scalability
• Cache aside
• CQRS
• Event Sourcing
• Index Table
• Materialized View
Resilency
• Bulk Head
• Circuit Breaker
• Compensating
Transaction
• Heald Endpoint
Monitor
• Leader Election
• Retry
Tổng hợp từ tài liệu Microservice Design Pattern của Microsoft
• API Gateway
• Service Discovery
• Logging / Monitoring
• Separate Database
• Message Queue
• REST, GRPC, WebSocket, Upload
Binary
Các pattern căn bản hay dùng
Không dùng API Gateway,
client sẽ phải quản lý
rất nhiều API end point
API Gateway:
- routing ~ reverse proxy
- authenticate
- authorize
- service discovery
- throttle
- circuit breaker
Nginx HAProxy Kong Tyk Go micro
Reverse Proxy ✔ ✔ ✔ ✔
Plugin ✔ ✔ ✔ ✔
Easy customize configure ✔ ✔ ✔ code
Language C/C++ LUA Go Go
Service
Discovery
không rõ ✔ ✔ ✔ consul
Authenticate plugin plugin plugin code your self
DevOps
friendly
DevOps
friendly
DevOps
friendly
Developer
friendly
https://github.com/micro/go-micro
• Mã nguồn mở + rất nhiều ví dụ
• Service discovery & configuration
• Viết bằng Golang, dễ hiểu
• GRPC request – reply, pub - sub
• Chuyển đổi GRPC ←→ REST
Tác giả Asim Aslam
https://github.com/micro/go-micro
• Quản lý microservice dạng GRPC hoặc Web
HTTP (Microservice GRPC không hỗ trợ REST và upload binary
mặc định, mà phải chuyển đổi)
• Hướng dẫn tự viết plugin bằng Golang
• Hỗ trợ tích hợp Nat.io, Kafka, RabbitMQ...
Chọn Golang?
• Ưu
– Dễ học – thực thi nhanh – tiết kiệm bộ nhớ
– Biên dịch ra binary không cần cài run time (JVM, .NET core) hay interpreter-
compiler (nodejs, python)
– Cần tạo ra nhiều microservice trong Docker container, nhưng không được
tốn quá nhiều bộ nhớ, dung lương đĩa
• Nhược
– Ít lập trình viên. Techmaster tự đào tạo trong 2 tháng
– Thư viện không đa dạng như Node.js và Java nhưng cũng đủ dùng
Communicate
Style
Request /
Response
Blocking
Sync
Non blocking
Async
Pub Sub
Broker
Broker less
Truyền thông giữa microservices
Create-Update-Delete-Query
Inform an event happened
Định dạng truyền dữ liệu
REST/JSON gRPC
Protobuf
Thrift
Avro
REST / JSON gRPC / Protobuf
Browser, JavaScript friendly Best gRPC web Oct 2018
Data Encoding JSON: Text, human readable Protobuf binary
HTTP HTTP, HTTP 1.1 HTTP2 Ready
Encode / decode speed Slow Fast
Calling style Object + HTTP Verbs
(GET/POST/PUT/DELETE)
method + params in / out
Self documentation No Yes
Schema / structure validation No Yes
So sánh khi encode cùng 1 bản tin bằng JSON và Protobuf
ServerClient
request
response
REST / JSON
• Rất phổ biến, dễ hiểu – Noun + HTTP Verb method
• Định dạng dữ liệu JSON, XML, Text, Binary
• Không bắt buộc validate dữ liệu ở cả client và server. Dev tự code
• Client và server phải đọc – phân tích – chuyển đổi dữ liệu
• Phải dùng công cụ document API ngoài như Swagger, OpenAPI
gRPC - Protobuf
• gRPC = Google Remote Procedure Call ~ Verbs + Params
• Dùng protobuf để định nghĩa định dạng dữ liệu trao đổi giữa
2 bên
BA
protobuf
compile
stub
code
stub
code
syntax = "proto3";
package go.micro.srv.greeter;
service Say {
rpc Hello(Request) returns (Response) {}
}
message Request {
string name = 1;
}
message Response {
string msg = 1;
}
• Định nghĩa dịch vụ, hàm, kiểu dữ liệu truyền, nhận
• 2 phiên bản: proto2 và proto3
• protoc biên dịch protobuf ra stub code trên các
ngôn ngữ lập trình khác nhau
• Có gogobuf thêm một số tính năng mở rộng
Demo 1: go micro trên 1 máy dev
consul agent -dev -ui
ServerClient
protobuf
stub
code
stub
code
compile
request
response
Demo 1: go micro trên 1 máy dev
1. Khởi động consul: consul agent -ui -dev
2. Tạo protobuf
3. Biên dịch protobuf ra stub code
4. Viết method ở server
5. Viết client gọi method trên server
6. micro cli
7. micro api
8. micro web
syntax = "proto3";
package go.micro.srv.greeter;
service Say {
rpc Hello(Request) returns (Response) {}
}
message Request {
string name = 1;
}
message Response {
string msg = 1;
}
Biên dịch protobuf ra golang
protoc --proto_path=$GOPATH/src:. --micro_out=. --go_out=. *.proto
Phải biên dịch protobuf ra ngôn ngữ cụ thể Python, C, JavaScript,
Dart, Ruby...
Cho riêng
go micro service
Xuất ra golang
Sinh tài liệu từ protobuf
https://github.com/pseudomuto/protoc-gen-doc
#!/bin/sh
docker run --rm 
-v $(pwd)/doc:/out 
-v $(pwd)/srv/proto/hello:/protos 
pseudomuto/protoc-gen-doc
open -a "Google Chrome" doc/index.html
gendoc.sh
micro> list
consul
go.micro.api
go.micro.srv.greeter
micro> get go.micro.srv.greeter
micro> call go.micro.srv.greeter Say.Hello {"name": "John"}
{
"msg": "Hello John”
}
micro cli
Tập lệnh command line để giao tiếp nhanh với các microservices trong hệ thống
micro api
$ curl -d 'service=go.micro.srv.greeter' 
-d 'method=Say.Hello' 
-d 'request={"name": "John"}' 
http://localhost:8080/rpc
{"msg":"Hello John"}
browser /
web front
end
micro api
service A
service B
service C
REST/JSON gRPC
micro web
Gọi grpc method của micro
service từ giao diện web.
Debug trực quan
Demo 2: Thêm method
1. Sửa file protobuf, thêm method Add
2. Biên dịch lại protobuf
3. Bổ xung code
4. Gọi thử
syntax = "proto3";
package go.micro.srv.greeter;
service Say {
rpc Hello(Request) returns (Response) {}
rpc Add(OperandRequest) returns (NumResponse) {}
}
message Request {
string name = 1;
}
message Response {
string msg = 1;
}
message OperandRequest {
int64 a = 1;
int64 b = 2;
}
message NumResponse {
int64 result = 1;
}
Thêm method Add
Kiểu message vào
Kiểu message trả về
func (s *Say) Add(ctx context.Context,
req *hello.OperandRequest, rsp *hello.NumResponse) error {
log.Print("Received Say.Add request")
rsp.Result = req.A + req.B
return nil
}
2 microservice nói chuyện với nhau
khi chúng nhìn thấy nhau và hiểu được nhau
192.168.1.55 192.168.1.100
microservice
mesh
Một microservice
đổi IP hoặc chết
Một microservice
tham gia hệ thống
Tăng độ ổn định, dễ kết nối, chịu lỗi của micro service mesh ???
Service Discovery
service registry cho service mới
đăng ký và nhận dạng các service
khác
Service Segment
Phân cụm, bảo mật các
nhóm service
Service Configuration
Đồng bộ key/value store giữa
các node
Consul + gRPC là 2 công nghệ chính của go micro
Demo 3: microservice nhiều node
• Làm sao để các node nhìn thấy nhau và gọi được nhau?
– service discovery
– health check
• Tạo một mạng lưới consul server và agent kết nối với nhau
Consul Server – Mac
192.168.1.55
Consul Agent –Alpine
192.168.1.57
join
Consul Agent –Alpine2
192.168.1.58
join
Consul Agent –Alpine3
192.168.1.60
join
MacOSX host - 192.168.1.55
$ consul agent -ui -data-dir=/tmp/consul -node=boss -bootstrap -
bind=192.168.1.55 –server
VirtualBox Alpine - 192.168.1.57
$ consul agent -data-dir=/tmp/consul -node=alpine -bind=192.168.1.57 –
join=192.168.1.55
VirtualBox Alpine2 - 192.168.1.58
$ consul agent -data-dir=/tmp/consul -node=alpine2 -bind=192.168.1.58 –
join=192.168.1.57
VMWareFusion Alpine3 - 192.168.1.60
$ consul agent -data-dir=/tmp/consul -node=alpine3 -bind=192.168.1.60 –server –
join=192.168.1.58
Consul Server – Mac
192.168.1.55
Consul Agent –Alpine
192.168.1.57
join
Consul Agent –Alpine2
192.168.1.58
join
Consul Agent –Alpine3
192.168.1.60
join
production dùng docker swarm
• Mỗi docker container khởi động consul agent
khi boot up, tự tìm consul agent có sẵn sau
đó kết nối vào.
• Lập trình viên không phải ghi rõ địa chỉ IP để
gõ lệnh consul join
demo 4: thêm web service node
• gRPC microservice xử lý upload file kém, không trực tiếp trả
về REST API
• Web app có thể đăng ký service registry của consul, nhưng
chưa đăng ký được các method như gRPC microservice
Authentication - Authorization
• Chốt chặn ở các đường vào khu đô thị
– Bảo vệ từng toà nhà
• Tự mỗi gia đình phải khoá cửa chính
– Trong một căn hộ lại có khoá cửa phòng
» Có tủ, két sắt
Phân quyền method tập trung tại api gate way
• Do consul lưu trữ service registry, tận dụng micro api làm
api gateway để xác minh
– Can “John” calls Blog.EditPost method ?
• Yes  Go Next
• No  Return error message
Phân quyền method
Phân quyền tác động lên đối tượng
do từng microservice quyết định
• Qua chốt kiểm tra quyền gọi method, đến chốt kiểm tra
quyền tác động lên một đối tượng cụ thể
– Can “John” calls Blog.EditPost method ?
– Yes. “John” can calls Blog.EditPost !
– Can “John” calls Blog.EditPost on Post.ID = 10012?
Phần quyền tác động lên
đối tượng cụ thể trong microservice
browser /
web front
end
micro api
AuthService
BlogService
REST
plugin
intercept
request
Post 1002
Pub Sub Message Queue
go micro, gRPC không phải là tất cả !
• REST vẫn rất phổ biến. Trình duyệt chưa hỗ trợ
gRPC
• gRPC không hỗ trợ tốt upload binary
• Request – Reply Remote Procedure Call vẫn cần
thiết
• Pub Sub và MessageQueue sẽ chiếm ưu thế
Có nhiều lựa chọn cho message queue
• Broker vs Brokerless
• Kafka / RabbitMQ / Nat.io
• Tạm thời chúng tôi dùng Nat.io vì Nat.io
dùng protobuf và đơn giản
Tổng hợp trước khi hết giờ
1. Golang là lựa chọn tốt để code microserviceNhẹ,
không cần cài run time, library
2. Chưa thể bỏ REST vì nó quá phổ biến
3. gRPC hợp lý cho call request response.
4. Protobuf giúp định nghĩa tốt chi tiết dữ liệu vào – ra
kiêm văn bản API luôn
5. Consul làm service discovery tốt
7. gRPC hiệu suất cao, nhưng chuyển đổi gRPC sang
REST hiệu suất giảm
8. Hệ microservices sử dụng cả call request /reply và
pub/sub
9. Tách cơ sở dữ liệu khi xây dựng microservice rất
khó khăn, hãy chia nhỏ schema cho mỗi
microservice
Cảm ơn các bạn đã lắng nghe

More Related Content

What's hot

itlchn 20 - Kien truc he thong chung khoan - Phan 2
itlchn 20 - Kien truc he thong chung khoan - Phan 2itlchn 20 - Kien truc he thong chung khoan - Phan 2
itlchn 20 - Kien truc he thong chung khoan - Phan 2IT Expert Club
 
마이크로서비스 기반 클라우드 아키텍처 구성 모범 사례 - 윤석찬 (AWS 테크에반젤리스트)
마이크로서비스 기반 클라우드 아키텍처 구성 모범 사례 - 윤석찬 (AWS 테크에반젤리스트) 마이크로서비스 기반 클라우드 아키텍처 구성 모범 사례 - 윤석찬 (AWS 테크에반젤리스트)
마이크로서비스 기반 클라우드 아키텍처 구성 모범 사례 - 윤석찬 (AWS 테크에반젤리스트) Amazon Web Services Korea
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvCodelyTV
 
Apache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache CamelApache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache CamelOmi Om
 
[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩NHN FORWARD
 
Tiki.vn - How we scale as a tech startup
Tiki.vn - How we scale as a tech startupTiki.vn - How we scale as a tech startup
Tiki.vn - How we scale as a tech startupTung Ns
 
우아한 모노리스
우아한 모노리스우아한 모노리스
우아한 모노리스Arawn Park
 
golang과 websocket을 활용한 서버프로그래밍 - 장애없는 서버 런칭 도전기
golang과 websocket을 활용한 서버프로그래밍 - 장애없는 서버 런칭 도전기golang과 websocket을 활용한 서버프로그래밍 - 장애없는 서버 런칭 도전기
golang과 websocket을 활용한 서버프로그래밍 - 장애없는 서버 런칭 도전기Sangik Bae
 
ITLC HN 14 - Bizweb Microservices Architecture
ITLC HN 14  - Bizweb Microservices ArchitectureITLC HN 14  - Bizweb Microservices Architecture
ITLC HN 14 - Bizweb Microservices ArchitectureIT Expert Club
 
마이크로서비스를 위한 AWS 아키텍처 패턴 및 모범 사례 - AWS Summit Seoul 2017
마이크로서비스를 위한 AWS 아키텍처 패턴 및 모범 사례 - AWS Summit Seoul 2017마이크로서비스를 위한 AWS 아키텍처 패턴 및 모범 사례 - AWS Summit Seoul 2017
마이크로서비스를 위한 AWS 아키텍처 패턴 및 모범 사례 - AWS Summit Seoul 2017Amazon Web Services Korea
 
유니티 + Nodejs를 활용한 멀티플레이어 게임 개발하기
유니티 + Nodejs를 활용한 멀티플레이어 게임 개발하기유니티 + Nodejs를 활용한 멀티플레이어 게임 개발하기
유니티 + Nodejs를 활용한 멀티플레이어 게임 개발하기Kiyoung Moon
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbieDaeMyung Kang
 
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019min woog kim
 
Dual write strategies for microservices
Dual write strategies for microservicesDual write strategies for microservices
Dual write strategies for microservicesBilgin Ibryam
 
How to build massive service for advance
How to build massive service for advanceHow to build massive service for advance
How to build massive service for advanceDaeMyung Kang
 
WebAssembly Fundamentals
WebAssembly FundamentalsWebAssembly Fundamentals
WebAssembly FundamentalsKnoldus Inc.
 
High Concurrency Architecture at TIKI
High Concurrency Architecture at TIKIHigh Concurrency Architecture at TIKI
High Concurrency Architecture at TIKINghia Minh
 
Redis - Usability and Use Cases
Redis - Usability and Use CasesRedis - Usability and Use Cases
Redis - Usability and Use CasesFabrizio Farinacci
 

What's hot (20)

itlchn 20 - Kien truc he thong chung khoan - Phan 2
itlchn 20 - Kien truc he thong chung khoan - Phan 2itlchn 20 - Kien truc he thong chung khoan - Phan 2
itlchn 20 - Kien truc he thong chung khoan - Phan 2
 
마이크로서비스 기반 클라우드 아키텍처 구성 모범 사례 - 윤석찬 (AWS 테크에반젤리스트)
마이크로서비스 기반 클라우드 아키텍처 구성 모범 사례 - 윤석찬 (AWS 테크에반젤리스트) 마이크로서비스 기반 클라우드 아키텍처 구성 모범 사례 - 윤석찬 (AWS 테크에반젤리스트)
마이크로서비스 기반 클라우드 아키텍처 구성 모범 사례 - 윤석찬 (AWS 테크에반젤리스트)
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytv
 
Apache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache CamelApache ActiveMQ and Apache Camel
Apache ActiveMQ and Apache Camel
 
[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩
 
Sapo Microservices Architecture
Sapo Microservices ArchitectureSapo Microservices Architecture
Sapo Microservices Architecture
 
Tiki.vn - How we scale as a tech startup
Tiki.vn - How we scale as a tech startupTiki.vn - How we scale as a tech startup
Tiki.vn - How we scale as a tech startup
 
우아한 모노리스
우아한 모노리스우아한 모노리스
우아한 모노리스
 
golang과 websocket을 활용한 서버프로그래밍 - 장애없는 서버 런칭 도전기
golang과 websocket을 활용한 서버프로그래밍 - 장애없는 서버 런칭 도전기golang과 websocket을 활용한 서버프로그래밍 - 장애없는 서버 런칭 도전기
golang과 websocket을 활용한 서버프로그래밍 - 장애없는 서버 런칭 도전기
 
ITLC HN 14 - Bizweb Microservices Architecture
ITLC HN 14  - Bizweb Microservices ArchitectureITLC HN 14  - Bizweb Microservices Architecture
ITLC HN 14 - Bizweb Microservices Architecture
 
마이크로서비스를 위한 AWS 아키텍처 패턴 및 모범 사례 - AWS Summit Seoul 2017
마이크로서비스를 위한 AWS 아키텍처 패턴 및 모범 사례 - AWS Summit Seoul 2017마이크로서비스를 위한 AWS 아키텍처 패턴 및 모범 사례 - AWS Summit Seoul 2017
마이크로서비스를 위한 AWS 아키텍처 패턴 및 모범 사례 - AWS Summit Seoul 2017
 
유니티 + Nodejs를 활용한 멀티플레이어 게임 개발하기
유니티 + Nodejs를 활용한 멀티플레이어 게임 개발하기유니티 + Nodejs를 활용한 멀티플레이어 게임 개발하기
유니티 + Nodejs를 활용한 멀티플레이어 게임 개발하기
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbie
 
Rest API
Rest APIRest API
Rest API
 
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
 
Dual write strategies for microservices
Dual write strategies for microservicesDual write strategies for microservices
Dual write strategies for microservices
 
How to build massive service for advance
How to build massive service for advanceHow to build massive service for advance
How to build massive service for advance
 
WebAssembly Fundamentals
WebAssembly FundamentalsWebAssembly Fundamentals
WebAssembly Fundamentals
 
High Concurrency Architecture at TIKI
High Concurrency Architecture at TIKIHigh Concurrency Architecture at TIKI
High Concurrency Architecture at TIKI
 
Redis - Usability and Use Cases
Redis - Usability and Use CasesRedis - Usability and Use Cases
Redis - Usability and Use Cases
 

Similar to Go micro framework to build microservices

Itlc2015
Itlc2015Itlc2015
Itlc2015Huy Do
 
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015IT Expert Club
 
Technical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnTechnical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnAsahina Infotech
 
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...DevDay.org
 
VoIP with Opensips
VoIP with OpensipsVoIP with Opensips
VoIP with OpensipsTrần Thanh
 
Lập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnLập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnSon Nguyen
 
Postgresql các vấn đề thực tế
Postgresql các vấn đề thực tếPostgresql các vấn đề thực tế
Postgresql các vấn đề thực tếTechMaster Vietnam
 
Introduction to python 20110917
Introduction to python   20110917Introduction to python   20110917
Introduction to python 20110917AiTi Education
 
Authentication and Authorization
Authentication and AuthorizationAuthentication and Authorization
Authentication and AuthorizationTechMaster Vietnam
 
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...VKhang Yang
 
Lập trình Python GUI vs PySide
Lập trình Python GUI vs PySideLập trình Python GUI vs PySide
Lập trình Python GUI vs PySideChien Dang
 
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cậnTrần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cậnSecurity Bootcamp
 
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSXHướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSXTechMaster Vietnam
 
Code Refactoring: Thay đổi nhỏ - Lợi ích lớn
Code Refactoring: Thay đổi nhỏ - Lợi ích lớnCode Refactoring: Thay đổi nhỏ - Lợi ích lớn
Code Refactoring: Thay đổi nhỏ - Lợi ích lớnNhật Nguyễn Khắc
 

Similar to Go micro framework to build microservices (20)

Arrowjs.io
Arrowjs.ioArrowjs.io
Arrowjs.io
 
Itlc2015
Itlc2015Itlc2015
Itlc2015
 
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
 
Technical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnTechnical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vn
 
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
 
VoIP with Opensips
VoIP with OpensipsVoIP with Opensips
VoIP with Opensips
 
Lập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnLập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biến
 
Postgresql các vấn đề thực tế
Postgresql các vấn đề thực tếPostgresql các vấn đề thực tế
Postgresql các vấn đề thực tế
 
Introduction to python 20110917
Introduction to python   20110917Introduction to python   20110917
Introduction to python 20110917
 
Báo cáo tuần đồ án
Báo cáo tuần đồ ánBáo cáo tuần đồ án
Báo cáo tuần đồ án
 
Node.js căn bản
Node.js căn bảnNode.js căn bản
Node.js căn bản
 
Authentication and Authorization
Authentication and AuthorizationAuthentication and Authorization
Authentication and Authorization
 
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
 
Lập trình Python GUI vs PySide
Lập trình Python GUI vs PySideLập trình Python GUI vs PySide
Lập trình Python GUI vs PySide
 
Code Camp #1
Code Camp #1Code Camp #1
Code Camp #1
 
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cậnTrần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cận
 
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSXHướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
 
Code Refactoring: Thay đổi nhỏ - Lợi ích lớn
Code Refactoring: Thay đổi nhỏ - Lợi ích lớnCode Refactoring: Thay đổi nhỏ - Lợi ích lớn
Code Refactoring: Thay đổi nhỏ - Lợi ích lớn
 
Clean code
Clean codeClean code
Clean code
 
Dsd05 01-rpca
Dsd05 01-rpcaDsd05 01-rpca
Dsd05 01-rpca
 

More from TechMaster Vietnam

Chia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTTChia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTTTechMaster Vietnam
 
Cơ sở dữ liệu postgres
Cơ sở dữ liệu postgresCơ sở dữ liệu postgres
Cơ sở dữ liệu postgresTechMaster Vietnam
 
Tìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tớiTìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tớiTechMaster Vietnam
 
Cấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phútCấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phútTechMaster Vietnam
 
Manage your project differently
Manage your project differentlyManage your project differently
Manage your project differentlyTechMaster Vietnam
 
Day0: Giới thiệu lập trình ứng dụng Apple iOS
Day0: Giới thiệu lập trình ứng dụng Apple iOSDay0: Giới thiệu lập trình ứng dụng Apple iOS
Day0: Giới thiệu lập trình ứng dụng Apple iOSTechMaster Vietnam
 
Bài trình bày cho sinh viên Bách Khoa 9/2012
Bài trình bày cho sinh viên Bách Khoa 9/2012Bài trình bày cho sinh viên Bách Khoa 9/2012
Bài trình bày cho sinh viên Bách Khoa 9/2012TechMaster Vietnam
 

More from TechMaster Vietnam (20)

Neural Network from Scratch
Neural Network from ScratchNeural Network from Scratch
Neural Network from Scratch
 
Flutter vs React Native 2018
Flutter vs React Native 2018Flutter vs React Native 2018
Flutter vs React Native 2018
 
C đến C++ phần 1
C đến C++ phần 1C đến C++ phần 1
C đến C++ phần 1
 
Control structure in C
Control structure in CControl structure in C
Control structure in C
 
Basic C programming
Basic C programmingBasic C programming
Basic C programming
 
Postgresql security
Postgresql securityPostgresql security
Postgresql security
 
Knex Postgresql Migration
Knex Postgresql MigrationKnex Postgresql Migration
Knex Postgresql Migration
 
Minimum Viable Products
Minimum Viable ProductsMinimum Viable Products
Minimum Viable Products
 
Chia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTTChia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTT
 
Cơ sở dữ liệu postgres
Cơ sở dữ liệu postgresCơ sở dữ liệu postgres
Cơ sở dữ liệu postgres
 
Tìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tớiTìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tới
 
iOS Master - Detail & TabBar
iOS Master - Detail & TabBariOS Master - Detail & TabBar
iOS Master - Detail & TabBar
 
Phalcon căn bản
Phalcon căn bảnPhalcon căn bản
Phalcon căn bản
 
Cấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phútCấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phút
 
Phalcon introduction
Phalcon introductionPhalcon introduction
Phalcon introduction
 
Slide that wins
Slide that winsSlide that wins
Slide that wins
 
Manage your project differently
Manage your project differentlyManage your project differently
Manage your project differently
 
Day0: Giới thiệu lập trình ứng dụng Apple iOS
Day0: Giới thiệu lập trình ứng dụng Apple iOSDay0: Giới thiệu lập trình ứng dụng Apple iOS
Day0: Giới thiệu lập trình ứng dụng Apple iOS
 
Bài trình bày cho sinh viên Bách Khoa 9/2012
Bài trình bày cho sinh viên Bách Khoa 9/2012Bài trình bày cho sinh viên Bách Khoa 9/2012
Bài trình bày cho sinh viên Bách Khoa 9/2012
 
Making a living
Making a livingMaking a living
Making a living
 

Go micro framework to build microservices

  • 1. Xây dựng Go microservice với Golang cuong@techmaster.vn Tải slide bit.ly/gomicro
  • 2. Agenda • Pattern phổ biến trong microservices • GRPC Protobuf vs REST • Go Micro / Service Discovery / Consul • Request Response vs Pub Sub / Nat.io
  • 3. Monolithic sang microservices • Không chạy theo trào lưu • Giải quyết vấn đề hiện tại (khó bảo trì, không bảo mật code) • Học hỏi kinh nghiệm của người đi trước • Tận dụng mã nguồn mở • Từ nhỏ đến lớn
  • 4. Pattern, lựa chọn công nghệ cho microservices thì quá nhiều
  • 5. Availability • Health Endpoint Monitoring • Queue based Load Leveling • Throttling Data Management • Cache Aside • CQRS • Event Sourcing • Index Table • Materialized View • Sharding • Static Content • Valet Key Messaging • Competing Consumers • Pipes and Filter • Priority Queue • Queue – Load Balancing • Scheduler – Agent - Supervisor Tổng hợp từ tài liệu Microservice Design Pattern của Microsoft
  • 6. Management and Monitor • Ambassador • Anti Corruption Layer • External Configuration Store • Gateway Aggregation • Gateway Offloading • Gateway Routing • SideCar • Strangler Performance Scalability • Cache aside • CQRS • Event Sourcing • Index Table • Materialized View Resilency • Bulk Head • Circuit Breaker • Compensating Transaction • Heald Endpoint Monitor • Leader Election • Retry Tổng hợp từ tài liệu Microservice Design Pattern của Microsoft
  • 7. • API Gateway • Service Discovery • Logging / Monitoring • Separate Database • Message Queue • REST, GRPC, WebSocket, Upload Binary Các pattern căn bản hay dùng
  • 8. Không dùng API Gateway, client sẽ phải quản lý rất nhiều API end point
  • 9. API Gateway: - routing ~ reverse proxy - authenticate - authorize - service discovery - throttle - circuit breaker
  • 10. Nginx HAProxy Kong Tyk Go micro Reverse Proxy ✔ ✔ ✔ ✔ Plugin ✔ ✔ ✔ ✔ Easy customize configure ✔ ✔ ✔ code Language C/C++ LUA Go Go Service Discovery không rõ ✔ ✔ ✔ consul Authenticate plugin plugin plugin code your self DevOps friendly DevOps friendly DevOps friendly Developer friendly
  • 11. https://github.com/micro/go-micro • Mã nguồn mở + rất nhiều ví dụ • Service discovery & configuration • Viết bằng Golang, dễ hiểu • GRPC request – reply, pub - sub • Chuyển đổi GRPC ←→ REST Tác giả Asim Aslam
  • 12. https://github.com/micro/go-micro • Quản lý microservice dạng GRPC hoặc Web HTTP (Microservice GRPC không hỗ trợ REST và upload binary mặc định, mà phải chuyển đổi) • Hướng dẫn tự viết plugin bằng Golang • Hỗ trợ tích hợp Nat.io, Kafka, RabbitMQ...
  • 13. Chọn Golang? • Ưu – Dễ học – thực thi nhanh – tiết kiệm bộ nhớ – Biên dịch ra binary không cần cài run time (JVM, .NET core) hay interpreter- compiler (nodejs, python) – Cần tạo ra nhiều microservice trong Docker container, nhưng không được tốn quá nhiều bộ nhớ, dung lương đĩa • Nhược – Ít lập trình viên. Techmaster tự đào tạo trong 2 tháng – Thư viện không đa dạng như Node.js và Java nhưng cũng đủ dùng
  • 14. Communicate Style Request / Response Blocking Sync Non blocking Async Pub Sub Broker Broker less Truyền thông giữa microservices Create-Update-Delete-Query Inform an event happened
  • 15. Định dạng truyền dữ liệu REST/JSON gRPC Protobuf Thrift Avro
  • 16. REST / JSON gRPC / Protobuf Browser, JavaScript friendly Best gRPC web Oct 2018 Data Encoding JSON: Text, human readable Protobuf binary HTTP HTTP, HTTP 1.1 HTTP2 Ready Encode / decode speed Slow Fast Calling style Object + HTTP Verbs (GET/POST/PUT/DELETE) method + params in / out Self documentation No Yes Schema / structure validation No Yes
  • 17. So sánh khi encode cùng 1 bản tin bằng JSON và Protobuf
  • 18. ServerClient request response REST / JSON • Rất phổ biến, dễ hiểu – Noun + HTTP Verb method • Định dạng dữ liệu JSON, XML, Text, Binary • Không bắt buộc validate dữ liệu ở cả client và server. Dev tự code • Client và server phải đọc – phân tích – chuyển đổi dữ liệu • Phải dùng công cụ document API ngoài như Swagger, OpenAPI
  • 19. gRPC - Protobuf • gRPC = Google Remote Procedure Call ~ Verbs + Params • Dùng protobuf để định nghĩa định dạng dữ liệu trao đổi giữa 2 bên BA protobuf compile stub code stub code
  • 20. syntax = "proto3"; package go.micro.srv.greeter; service Say { rpc Hello(Request) returns (Response) {} } message Request { string name = 1; } message Response { string msg = 1; } • Định nghĩa dịch vụ, hàm, kiểu dữ liệu truyền, nhận • 2 phiên bản: proto2 và proto3 • protoc biên dịch protobuf ra stub code trên các ngôn ngữ lập trình khác nhau • Có gogobuf thêm một số tính năng mở rộng
  • 21. Demo 1: go micro trên 1 máy dev consul agent -dev -ui ServerClient protobuf stub code stub code compile request response
  • 22. Demo 1: go micro trên 1 máy dev 1. Khởi động consul: consul agent -ui -dev 2. Tạo protobuf 3. Biên dịch protobuf ra stub code 4. Viết method ở server 5. Viết client gọi method trên server 6. micro cli 7. micro api 8. micro web
  • 23. syntax = "proto3"; package go.micro.srv.greeter; service Say { rpc Hello(Request) returns (Response) {} } message Request { string name = 1; } message Response { string msg = 1; }
  • 24. Biên dịch protobuf ra golang protoc --proto_path=$GOPATH/src:. --micro_out=. --go_out=. *.proto Phải biên dịch protobuf ra ngôn ngữ cụ thể Python, C, JavaScript, Dart, Ruby... Cho riêng go micro service Xuất ra golang
  • 25. Sinh tài liệu từ protobuf https://github.com/pseudomuto/protoc-gen-doc #!/bin/sh docker run --rm -v $(pwd)/doc:/out -v $(pwd)/srv/proto/hello:/protos pseudomuto/protoc-gen-doc open -a "Google Chrome" doc/index.html gendoc.sh
  • 26. micro> list consul go.micro.api go.micro.srv.greeter micro> get go.micro.srv.greeter micro> call go.micro.srv.greeter Say.Hello {"name": "John"} { "msg": "Hello John” } micro cli Tập lệnh command line để giao tiếp nhanh với các microservices trong hệ thống
  • 27. micro api $ curl -d 'service=go.micro.srv.greeter' -d 'method=Say.Hello' -d 'request={"name": "John"}' http://localhost:8080/rpc {"msg":"Hello John"} browser / web front end micro api service A service B service C REST/JSON gRPC
  • 28. micro web Gọi grpc method của micro service từ giao diện web. Debug trực quan
  • 29. Demo 2: Thêm method 1. Sửa file protobuf, thêm method Add 2. Biên dịch lại protobuf 3. Bổ xung code 4. Gọi thử
  • 30. syntax = "proto3"; package go.micro.srv.greeter; service Say { rpc Hello(Request) returns (Response) {} rpc Add(OperandRequest) returns (NumResponse) {} } message Request { string name = 1; } message Response { string msg = 1; } message OperandRequest { int64 a = 1; int64 b = 2; } message NumResponse { int64 result = 1; } Thêm method Add Kiểu message vào Kiểu message trả về
  • 31. func (s *Say) Add(ctx context.Context, req *hello.OperandRequest, rsp *hello.NumResponse) error { log.Print("Received Say.Add request") rsp.Result = req.A + req.B return nil }
  • 32.
  • 33. 2 microservice nói chuyện với nhau khi chúng nhìn thấy nhau và hiểu được nhau 192.168.1.55 192.168.1.100
  • 35. Một microservice đổi IP hoặc chết Một microservice tham gia hệ thống
  • 36. Tăng độ ổn định, dễ kết nối, chịu lỗi của micro service mesh ??? Service Discovery service registry cho service mới đăng ký và nhận dạng các service khác Service Segment Phân cụm, bảo mật các nhóm service Service Configuration Đồng bộ key/value store giữa các node Consul + gRPC là 2 công nghệ chính của go micro
  • 37. Demo 3: microservice nhiều node • Làm sao để các node nhìn thấy nhau và gọi được nhau? – service discovery – health check • Tạo một mạng lưới consul server và agent kết nối với nhau
  • 38. Consul Server – Mac 192.168.1.55 Consul Agent –Alpine 192.168.1.57 join Consul Agent –Alpine2 192.168.1.58 join Consul Agent –Alpine3 192.168.1.60 join
  • 39. MacOSX host - 192.168.1.55 $ consul agent -ui -data-dir=/tmp/consul -node=boss -bootstrap - bind=192.168.1.55 –server VirtualBox Alpine - 192.168.1.57 $ consul agent -data-dir=/tmp/consul -node=alpine -bind=192.168.1.57 – join=192.168.1.55 VirtualBox Alpine2 - 192.168.1.58 $ consul agent -data-dir=/tmp/consul -node=alpine2 -bind=192.168.1.58 – join=192.168.1.57 VMWareFusion Alpine3 - 192.168.1.60 $ consul agent -data-dir=/tmp/consul -node=alpine3 -bind=192.168.1.60 –server – join=192.168.1.58
  • 40. Consul Server – Mac 192.168.1.55 Consul Agent –Alpine 192.168.1.57 join Consul Agent –Alpine2 192.168.1.58 join Consul Agent –Alpine3 192.168.1.60 join
  • 41.
  • 42. production dùng docker swarm • Mỗi docker container khởi động consul agent khi boot up, tự tìm consul agent có sẵn sau đó kết nối vào. • Lập trình viên không phải ghi rõ địa chỉ IP để gõ lệnh consul join
  • 43. demo 4: thêm web service node • gRPC microservice xử lý upload file kém, không trực tiếp trả về REST API • Web app có thể đăng ký service registry của consul, nhưng chưa đăng ký được các method như gRPC microservice
  • 44.
  • 46. • Chốt chặn ở các đường vào khu đô thị – Bảo vệ từng toà nhà • Tự mỗi gia đình phải khoá cửa chính – Trong một căn hộ lại có khoá cửa phòng » Có tủ, két sắt
  • 47. Phân quyền method tập trung tại api gate way • Do consul lưu trữ service registry, tận dụng micro api làm api gateway để xác minh – Can “John” calls Blog.EditPost method ? • Yes  Go Next • No  Return error message Phân quyền method
  • 48. Phân quyền tác động lên đối tượng do từng microservice quyết định • Qua chốt kiểm tra quyền gọi method, đến chốt kiểm tra quyền tác động lên một đối tượng cụ thể – Can “John” calls Blog.EditPost method ? – Yes. “John” can calls Blog.EditPost ! – Can “John” calls Blog.EditPost on Post.ID = 10012? Phần quyền tác động lên đối tượng cụ thể trong microservice
  • 49. browser / web front end micro api AuthService BlogService REST plugin intercept request Post 1002
  • 51. go micro, gRPC không phải là tất cả ! • REST vẫn rất phổ biến. Trình duyệt chưa hỗ trợ gRPC • gRPC không hỗ trợ tốt upload binary • Request – Reply Remote Procedure Call vẫn cần thiết • Pub Sub và MessageQueue sẽ chiếm ưu thế
  • 52. Có nhiều lựa chọn cho message queue • Broker vs Brokerless • Kafka / RabbitMQ / Nat.io • Tạm thời chúng tôi dùng Nat.io vì Nat.io dùng protobuf và đơn giản
  • 53. Tổng hợp trước khi hết giờ
  • 54. 1. Golang là lựa chọn tốt để code microserviceNhẹ, không cần cài run time, library 2. Chưa thể bỏ REST vì nó quá phổ biến 3. gRPC hợp lý cho call request response. 4. Protobuf giúp định nghĩa tốt chi tiết dữ liệu vào – ra kiêm văn bản API luôn 5. Consul làm service discovery tốt
  • 55. 7. gRPC hiệu suất cao, nhưng chuyển đổi gRPC sang REST hiệu suất giảm 8. Hệ microservices sử dụng cả call request /reply và pub/sub 9. Tách cơ sở dữ liệu khi xây dựng microservice rất khó khăn, hãy chia nhỏ schema cho mỗi microservice
  • 56. Cảm ơn các bạn đã lắng nghe