In-Memory Database là gì?
In-memory database là hệ thống quản lý database chủ yếu dựa trên main memory (RAM) để lưu trữ dữ liệu. In-memory database nhanh hơn disk-optimized database vì truy cập disk chậm hơn truy cập memory. Truy cập dữ liệu trong memory loại bỏ seek time khi query, cung cấp hiệu suất nhanh hơn và dự đoán được hơn so với disk. Có nhiều in-memory database với license khác nhau. Bài viết thảo luận về Redis - một trong những in-memory database mã nguồn mở nổi tiếng nhất.
Lợi ích của In-Memory Database
- Hỗ trợ quản lý big data
- Cho phép cập nhật real-time, giúp doanh nghiệp truy cập dữ liệu ngay khi xảy ra
- Dùng cho ứng dụng yêu cầu truy cập, lưu trữ và thao tác dữ liệu cực nhanh
- Không chỉ giảm thời gian phản hồi query, mà còn giảm hoặc loại bỏ hoàn toàn nhu cầu indexing và lưu trữ pre-aggregated data trong OLAP cubes hoặc aggregate tables
Redis
Redis là dự án in-memory database mã nguồn mở triển khai distributed, in-memory key-value store với độ bền tùy chọn. Redis hỗ trợ nhiều cấu trúc dữ liệu trừu tượng: strings, lists, maps, sets, sorted sets, hyperlog, bitmaps, spatial indexes. Chi tiết tại Redis In-Memory Database.
Để dùng Redis trong ứng dụng, trước tiên cài đặt Redis database. Tải tại Download latest version of Redis In-Memory Database. Sau khi cài đặt xong, tạo một console application đơn giản để xem cách hoạt động.
Bước 1. Mở Visual Studio (đây dùng Microsoft Visual Studio 2015 Community Edition). File → New → Project. Tạo Console Application cho demo.

Bước 2. Kết nối Redis cần Redis Client từ NuGet. Trong Solution Explorer, right-click References → Manage NuGet Packages. Tìm ServiceStack.Redis.Complete và Install.

Bước 3. Code: tạo 2 static function, một insert giá trị vào Redis DB, một đọc từ DB.
Lưu dữ liệu vào Redis database:
///<summary>
///ToSaveKeyValuePairinRedisDB
///</summary>
///<param name="host">RedisHostName</param>
///<param name="key">Key as string</param>
///<param name="value">Value as string</param>
///<returns></returns>
private static bool Save(string host, string key, string value) {
using(var objRedisClient = new RedisClient(host)) {
if(objRedisClient.Get<string>(key) == null) {
return objRedisClient.Set<String>(key, value);
} else {
return false;
}
}
}
///<summary>
///TogetvaluefromRedisDB
///</summary>
///<param name="host">RedisHostName</param>
///<param name="key">Key as string</param>
///<returns></returns>
private static string Get(string host, string key) {
using(var objRedisClient = new RedisClient(host)) {
return objRedisClient.Get<String>(key);
}
}
Test bằng cách gọi 2 function:
static void Main(string[] args) {
Save("localhost", "Key1", "Value1");
var result = Get("localhost", "Key1");
}
Kết quả khi debug:

Kết luận
Bài viết đã trình bày triển khai cơ bản của Redis in-memory database. Bạn có thể tải source code mẫu đính kèm. Hy vọng bạn thích bài viết. Hãy tiếp tục đọc và đừng quên gửi phản hồi quý báu.