In-Memory Database คืออะไร?
ฐานข้อมูลแบบดั้งเดิมเก็บ "hot data" ใน RAM ส่วนที่เหลือบนดิสก์ Redis เน้น latency ต่ำ ดำเนินการทั้งหมดใน RAM (RAM-based) เร็วกว่ามาก
Redis เป็น key-value store แต่รองรับโครงสร้างข้อมูลหลากหลาย (strings, hashes, lists, sets, sorted sets, streams, geospatial, bitmaps, hyperloglogs)
ทำไมต้อง Redis?
- Stateless application: เก็บ state ใน Redis → code stateless → scale horizontally ได้
- Shared memory across services: บริการหลายตัว share ข้อมูลผ่าน Redis (เช่น block IP brute-force ทุก service)
Redis CLI (REPL)
รัน redis-cli → พิมพ์คำสั่งได้ทันที ใช้ debug/diagnose ได้สะดวก
คำสั่ง Redis ที่ใช้บ่อย
SET / GET
SET mehul "developer from india"
GET mehul # "developer from india"
SETNX (Set if Not Exists)
SET key1 value1
SETNX key1 value2 # ไม่ทำงาน key1 มีอยู่แล้ว
SETNX key2 value2 # สำเร็จ
MSET / MGET (Multiple)
MSET key1 "value1" key2 "value2" key3 "value3"
MGET key1 key2 key3 key4 # [value1, value2, value3, null]
DEL
DEL key
INCR / DECR (Atomic Counter)
SET favNum 10
INCR favNum # 11
INCR favNum # 12
DECR favNum # 11
EXPIRE / TTL / SETEX
SET bitcoin 100
EXPIRE bitcoin 10 # หมดอายุ 10 วินาที
TTL bitcoin # -1 (ไม่มี expiry), -2 (ไม่มี key), หรือวินาทีที่เหลือ
SETEX key 10 value # SET + EXPIRE พร้อมกัน
โปรเจกต์ 1: API Caching System
แคช GitHub stars ไว้ 60 วินาที ลด rate limit และเร่งความเร็ว
app.post('/data', async (req, res) => {
const repo = req.body.repo;
const value = await redis.get(repo);
if (value) return res.json({ status: 'ok', stars: value }); // cache hit
const response = await fetch(`https://api.github.com/repos/${repo}`).then(r => r.json());
if (response.stargazers_count != undefined) {
await redis.setex(repo, 60, response.stargazers_count);
}
res.json({ status: 'ok', stars: response.stargazers_count });
});
โปรเจกต์ 2: Rate Limiting API
จำกัด request ต่อ IP 15 req/2 วินาที
app.post('/api/route', async (req, res) => {
const ip = req.headers['x-forwarded-for'] || req.ip;
const reqs = await redis.incr(ip);
await redis.expire(ip, 2);
if (reqs > 15) return res.json({ status: 'rate-limited' });
else if (reqs > 10) return res.json({ status: 'about-to-rate-limit' });
res.json({ status: 'ok' });
});
หลักการสำคัญของ Redis
- Single-threaded: ไม่ใช่ bottleneck แต่เป็น safety measure ป้องกัน race condition
- Transactions (MULTI/EXEC): รันชุดคำสั่งแบบ atomic
- Pub/Sub: Broadcast ข้อความไปยัง subscribers
สรุป
Redis เรียนรู้ง่าย คำสั่งไม่มาก แต่พลังมาก เหมาะสำหรับ caching, rate limiting, session store, real-time messaging ลองลองคอร์ส interactive ที่ codedamn