Apa itu Redis?
Redis (Remote Dictionary Server) adalah in-memory key-value store yang sangat cepat. Data disimpan di RAM sehingga akses dalam mikrodetik.
Use Cases Redis
- Caching — simpan hasil query database yang sering diakses
- Session storage — simpan session user
- Rate limiting — batasi request per waktu
- Queue — antrian job/task
- Real-time — leaderboard, counter, pub/sub
Data Structures di Redis
-- String (key-value sederhana)
SET user:1:name "Budi"
GET user:1:name -- "Budi"
SET page:home:views 0
INCR page:home:views -- 1 (atomic increment)
-- Hash (object/map)
HSET user:1 name "Budi" email "[email protected]" age 25
HGET user:1 name -- "Budi"
HGETALL user:1 -- semua field
-- List (ordered, bisa push/pop)
LPUSH notifications:1 "Pesan baru"
LPUSH notifications:1 "Order dikirim"
LRANGE notifications:1 0 -1 -- semua notifikasi
-- Set (unique, unordered)
SADD user:1:roles "admin" "editor"
SISMEMBER user:1:roles "admin" -- true
-- Sorted Set (ranked)
ZADD leaderboard 100 "Budi" 85 "Siti" 92 "Andi"
ZREVRANGE leaderboard 0 2 -- top 3 tertinggi
TTL (Time To Live)
-- Set data dengan expiry otomatis
SET cache:products "[...]" EX 3600 -- expire dalam 1 jam
SETEX otp:08123 300 "123456" -- OTP expire 5 menit
TTL cache:products -- sisa waktu dalam detik
Redis di Laravel
// Caching
Cache::put('popular_products', $products, 3600);
$products = Cache::get('popular_products');
// Rate limiting
RateLimiter::attempt('send-otp:' . $user->id, 3, function () {
// kirim OTP
}, 60); // max 3x per 60 detik