SlideShare a Scribd company logo
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
}
Go micro framework to build microservices
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
Go micro framework to build microservices
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
Go micro framework to build microservices
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

PDF
Building Bizweb Microservices with Docker
PDF
Kinh nghiệm triển khai Microservices tại Sapo.vn
PDF
Bizweb Microservices Architecture
PPTX
Distributed Transaction in Microservice
PPTX
Software architecture for high traffic website
PDF
Postgresql các vấn đề thực tế
PDF
PPTX
Node.js Express
Building Bizweb Microservices with Docker
Kinh nghiệm triển khai Microservices tại Sapo.vn
Bizweb Microservices Architecture
Distributed Transaction in Microservice
Software architecture for high traffic website
Postgresql các vấn đề thực tế
Node.js Express

What's hot (20)

PPTX
Solid principles
PDF
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
PPTX
SFDC Batch Apex
PPTX
Rabbit MQ introduction
PDF
Continuous Delivery to Kubernetes with Jenkins and Helm
PDF
Refactoring
PPTX
Solid principles
PDF
ES2015 / ES6: Basics of modern Javascript
PDF
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
PDF
PromQL Deep Dive - The Prometheus Query Language
PDF
Introduction to Docker Compose
PPTX
React state
PDF
angular fundamentals.pdf
PPTX
Code smells and remedies
PPT
PHP Project PPT
PDF
Spring Security
PDF
Microservice - Up to 500k CCU
PPTX
JSON: The Basics
PDF
Model View Controller (MVC)
PPT
Developing an ASP.NET Web Application
Solid principles
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
SFDC Batch Apex
Rabbit MQ introduction
Continuous Delivery to Kubernetes with Jenkins and Helm
Refactoring
Solid principles
ES2015 / ES6: Basics of modern Javascript
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
PromQL Deep Dive - The Prometheus Query Language
Introduction to Docker Compose
React state
angular fundamentals.pdf
Code smells and remedies
PHP Project PPT
Spring Security
Microservice - Up to 500k CCU
JSON: The Basics
Model View Controller (MVC)
Developing an ASP.NET Web Application
Ad

Similar to Go micro framework to build microservices (20)

PDF
Sapo Microservices Architecture
PPTX
Arrowjs.io
PDF
Itlc2015
PPTX
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
PDF
Technical note playframework_documentation_working with play - java_vn
PPTX
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
PPTX
VoIP with Opensips
PPTX
Lập trình web với các công nghệ phổ biến
PDF
B3_10_2024_VHT_Cloud_Native_(Kubernetees_Basic__Practice).pdf
PPTX
ITLC HN 14 - Bizweb Microservices Architecture
PPTX
Introduction to python 20110917
DOCX
Báo cáo tuần đồ án
PDF
Node.js căn bản
PDF
Authentication and Authorization
PDF
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
PPTX
Lập trình Python GUI vs PySide
PPT
Code Camp #1
PPTX
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cận
PPTX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
PPTX
Code Refactoring: Thay đổi nhỏ - Lợi ích lớn
Sapo Microservices Architecture
Arrowjs.io
Itlc2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
Technical note playframework_documentation_working with play - java_vn
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
VoIP with Opensips
Lập trình web với các công nghệ phổ biến
B3_10_2024_VHT_Cloud_Native_(Kubernetees_Basic__Practice).pdf
ITLC HN 14 - Bizweb Microservices Architecture
Introduction to python 20110917
Báo cáo tuần đồ án
Node.js căn bản
Authentication and Authorization
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
Code Camp #1
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
Code Refactoring: Thay đổi nhỏ - Lợi ích lớn
Ad

More from TechMaster Vietnam (20)

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

Go micro framework to build microservices

  • 1. Xây dựng Go microservice với Golang [email protected] 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 }
  • 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
  • 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
  • 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