Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Tận dụng DynamoDB trong Ứng dụng Rails của Bạn

Cốt lõi, DynamoDB là NoSQL database cung cấp cấu trúc dữ liệu key-value và document. Hãy unpack điều này. Tôi tưởng tượng hầu hết dev đọc bài này khá quen với traditional relational database systems, liên quan đến well-defined schemas và data normalized vào tables, rows, columns. Giữa các tables có "relationships" dùng foreign keys. Ngược lại, DynamoDB là schemaless. Mọi table phải có primary key, nhưng không có constraint khác trên non-key attributes. Khi nào điều này có lợi? Hãy học tại sao Amazon tạo DynamoDB.

Amazon công bố kế hoạch release DynamoDB cho public use năm 2012. Amazon phát triển Dynamo nội bộ sau mùa lễ hội 2004, khi một số ứng dụng fail do lượng traffic cao.

Khi nào nên cân nhắc dùng DynamoDB?

DynamoDB là lựa chọn tốt cho app cần support rất lớn số lượng (nghìn+) concurrent users, do đó hàng chục nghìn reads/writes per second. Ví dụ: social networks, games, IoT devices có thể là candidate tốt cho DynamoDB; ví dụ Lyft, Airbnb, Redfin dùng Dynamo. Ngay cả adoption nhẹ ban đầu, và performance không cần thiết ngay, bắt đầu với DynamoDB có thể có lợi vs traditional SQL database như Postgres, nếu cuối cùng bạn sẽ build for scale. Tuy nhiên, nếu bạn build data warehouse hoặc OLAP app mà user thường xuyên query, schemaless database có lẽ không phải design choice tốt. Hơn nữa, trong khi RDBMS tối ưu cho storage, DynamoDB tối ưu cho compute. Amazon claim DynamoDB deliver single-digit millisecond performance ở mọi scale, handle 10 trillion+ requests/ngày, peak 20 triệu+ requests/giây. Wow!

Bên cạnh đó, AWS cung cấp suite features khác làm DynamoDB phù hợp cho app yêu cầu data retention và/hoặc security.

  • Encryption at rest: DynamoDB secure tất cả data trong encrypted table, bao gồm primary key. User chọn ba option: AWS-owned customer master key (CMK), AWS-managed CMK (key lưu trong account, managed by AWS KMS), hoặc customer-managed CMK (key lưu trong account, created/owned/managed bởi bạn). Cool là mỗi table có thể dùng option khác. Đọc thêm về encryption at rest tại AWS docs chính thức.

  • On-demand backups/point-in-time recovery: DynamoDB cho phép restore table đến bất kỳ point in time nào trong ~30 ngày qua. Hết lo lắng về accidental writes hoặc deletes!

Cơ bản của DynamoDB

DynamoDB có ba core components: tables, items, attributes. Hãy phân tích từng cái.

  • Table: collection của items
  • Item: collection của attributes
  • Attribute: fundamental data element không cần break down thêm.

Ví dụ, nếu tôi làm app quản lý rental properties, tôi có thể có table "Houses" với items sau:

{
  "HouseID": 1,
  "AddressLine1": "123 Main St",
  "City": "Atlanta",
  "State": "GA",
  "Zip": 30322,
  "Rented": true,
  "Tenant": "John Smith"
}
{
  "HouseID": 2,
  "AddressLine1": "456 Square St",
  "City": "Nashville",
  "State": "TN",
  "Zip": 37211,
  "Rented": true,
  "Tenant": "Mary Jane"
}

HouseID, AddressLine1, City, State, Zip, Rented và Tenant đều là attributes của items. Bạn có thể liken item như row và attribute như column trong traditional SQL database. Tuy nhiên, tôi khuyên cố gắng tránh so sánh NoSQL database như DynamoDB với traditional SQL database, vì chúng là beasts rất khác nhau.

Lưu ý mỗi item có unique primary key (DynamoDB hỗ trợ cả single partition keys và composite primary keys). Tuy nhiên, ngoài HouseID, table Houses là schemaless. Do đó, attributes và data types không cần define trước, khác traditional SQL database yêu cầu Zip define trong schema với type integer.

Bạn có thể thắc mắc indexes hoạt động thế nào với DynamoDB. Nếu vậy, câu hỏi hay! Hãy giả sử tôi muốn tạo index trên attributes rented và zip của table Houses (tức: given zip code, get all rented properties trong zip đó). Nếu dùng SQL database, tôi có thể tạo migration như:

CREATE INDEX RentedAndZipIndex ON Houses (rented, zip);

Ngược lại, nếu dùng DynamoDB, tôi muốn setup secondary index. Để làm này, phải chỉ định partition key và sort key. Ở ví dụ này, zip là partition key, rented là sort key. Còn nhiều hơn về indexes với DynamoDB, nhưng cho bài này để ở đây. Nếu quan tâm thêm, đọc thêm tại đây.

Sử dụng DynamoDB với Ruby và Ruby on Rails

AWS cung cấp SDKs nhiều ngôn ngữ cho DynamoDB (Java, JavaScript, Node.js, .NET, PHP, Python, Ruby hiện tại). Để dùng DynamoDB với Ruby, bạn có hai option:

1) Download DynamoDB local; nếu chỉ muốn test app, option tuyệt vời! Khi sẵn sàng production, bỏ local endpoint và point to web service.

2) Dùng DynamoDB web service, yêu cầu AWS access key và creds.

Để interact với DynamoDB, bạn có thể muốn download CLI. Nếu không, dùng console hoặc API.

Cuối cùng, cho series này, bạn cần cài Ruby, cũng như AWS SDK cho Ruby.

Cho Rails, có gem tiện lợi thêm vào project. Gọi là Dynamoid. Tuy nhiên, vẫn cần AWS credentials.

Ví dụ Rails

Bước 1: Setup

Trong Gemfile, thêm gems sau và chạy bundle install:

gem 'dynamoid'
gem 'aws-sdk'

Tiếp theo, tạo file mới aws.rb trong directory config/initializers và thêm:

Tận dụng DynamoDB trong Ứng dụng Rails của Bạn

Lưu ý: Nên dùng environment variables giữ credentials. Không bao giờ hard-code vào project!

Bước 2: Định nghĩa Document

Ví dụ này, tôi tạo file house.rb trong app/models trông như sau:

Tận dụng DynamoDB trong Ứng dụng Rails của Bạn

Hãy đi qua những gì có đây.

  • Bạn bắt buộc luôn include include Dynamoid::Document khi define tables.
  • Dòng 4, tôi define table name, key, capacity mode. Dynamoid gem có sensible defaults, nên technically không cần include các trên. Tuy nhiên, define chúng sẽ override defaults. Bạn cũng define read_capacity và write_capacity. Tuy nhiên, vì tôi define capacity_mode là on_demand, các option đó bị ignore vì on_demand capacity mode bảo AWS tự scale up/down.
  • Tiếp theo, define fields cho table. Bạn phải define tất cả fields trên model, cũng như data type (sẽ assume string nếu omit).

Gem dynamoid có rake task tiện tạo table.

rake dynamoid:create_tables

Bước 3: Tương tác với Objects

Mặc dù có vẻ lạ, tin tốt: phần lớn features bạn quen với Active Record hoạt động rất giống.

Associations

Ví dụ, Dynamoid hỗ trợ nhiều associations: has_many, has_one, has_and_belongs_to_many, belongs_to đều define giống như ActiveRecord. Bạn tưởng tượng rental properties app có document table khác Lease, nên trên table House có thể define:

has_one :lease

và trên table Lease:

belongs_to :house

Validations

Dynamoid cũng baked in ActiveModel validations, nên bạn all set! Documentation available tại đây.

Callbacks

before_ hoặc after_ callbacks available cho actions save, update, destroy, nên có thể define như sau trong lease.rb:

before_save :validate_signature

Creation

Lại nữa, syntax tạo objects trông giống hệt ActiveRecord. Có thể làm:

h = House.new(address_line_1: "123 Main St", city: "Cool City", state: "Iowa", zip: 52302)
h.rented = true
h.save

Hoặc đơn giản dùng method .create:

House.create(address_line_1: "123 Main St", city: "Cool City", state: "Iowa", zip: 52302)

Querying

Biết tôi nghe như broken record, nhưng bạn đoán querying hoạt động thế nào? Đúng, giống ActiveRecord.

  • .find nhận ID
  • .where nhận bất kỳ matching criteria nào
  • .find_by_x với x là attribute.

Muốn thêm?

Còn rất nhiều để học về Dynamoid gem, nhưng hy vọng đủ để bạn bắt đầu chơi. Khuyến khích check official GitHub page tại đây đọc thêm features available!

Tiếp theo

Nhiều thứ để tiêu hóa! Hy vọng bạn cảm thấy am hiểu hơn về nghĩa khi ai nói 'NoSQL' và tại sao DynamoDB có thể là lựa chọn tốt cho project cần schemaless database. Ngoài ra, chúng ta đã walk through basic setup dùng dynamoid gem với Rails project.

Trong bài tiếp theo của series, chúng ta sẽ setup DynamoDB local và thử một số features của Ruby SDK.