Redis có 5 kiểu dữ liệu cơ bản (String, Hash, List, Set, Sorted Set), mỗi loại tối ưu cho một use case khác nhau.
Các kiểu dữ liệu Redis và khi nào dùng:
- String: kiểu cơ bản nhất, dùng cho cache HTML/JSON, counter (
INCR pageview), session token. Lệnh:SET key value EX 3600,GET key,INCR counter. - Hash: lưu object có nhiều field (như row trong database), hiệu quả hơn lưu từng field dưới dạng String riêng. Dùng cho: user profile, product info. Lệnh:
HSET user:1 name 'Alice' age 30,HGETALL user:1. - List: linked list có thể push/pop từ cả hai đầu — dùng cho message queue, activity feed, recent items. Lệnh:
LPUSH queue task1,RPOP queue. - Set: tập hợp unique member — dùng cho tags, unique visitors, friend list. Lệnh:
SADD tags:post:1 redis database,SISMEMBER,SUNION. - Sorted Set: như Set nhưng mỗi member có score — dùng cho leaderboard, rate limiting, priority queue. Lệnh:
ZADD leaderboard 1000 'Alice',ZRANGE leaderboard 0 9 REV WITHSCORES.
Redis has 5 core data types (String, Hash, List, Set, Sorted Set), each optimised for a different use case.
Redis data types and when to use them:
- String: the most basic type, used for caching HTML/JSON, counters (
INCR pageview), and session tokens. Commands:SET key value EX 3600,GET key,INCR counter. - Hash: stores objects with multiple fields (like a database row), more efficient than individual String keys per field. Use for user profiles, product info. Commands:
HSET user:1 name Alice age 30,HGETALL user:1. - List: a doubly-linked list supporting push/pop from both ends — used for message queues, activity feeds, and recent-items lists. Commands:
LPUSH queue task1,RPOP queue. - Set: a collection of unique members — used for tags, unique visitor tracking, and friend lists. Commands:
SADD tags:post:1 redis database,SISMEMBER,SUNION. - Sorted Set: like a Set but each member has a score — used for leaderboards, rate limiting, and priority queues. Commands:
ZADD leaderboard 1000 Alice,ZRANGE leaderboard 0 9 REV WITHSCORES.