์ฝ˜ํ…์ธ  ๋Œ€ํ‘œ ์ด๋ฏธ์ง€ - ๐Ÿš€ ์‘์šฉํ”„๋กœ๊ทธ๋ž˜๋ฐ์—์„œ ์บ์‹ฑ ๊ธฐ๋ฒ• ์ ์šฉํ•˜๊ธฐ

๐Ÿš€ ์‘์šฉํ”„๋กœ๊ทธ๋ž˜๋ฐ์—์„œ ์บ์‹ฑ ๊ธฐ๋ฒ• ์ ์šฉํ•˜๊ธฐ

Redis์™€ Memcached๋กœ ์„ฑ๋Šฅ ํญ๋ฐœ์‹œํ‚ค๊ธฐ ๐Ÿ’ฅ
์นœ๊ตฌ์ฒ˜๋Ÿผ ์‰ฝ๊ฒŒ ์•Œ๋ ค์ฃผ๋Š” ์บ์‹ฑ์˜ ๋ชจ๋“  ๊ฒƒ
## ๐ŸŽฏ ์บ์‹ฑ, ์™œ ํ•„์š”ํ•œ ๊ฑฐ์•ผ? ์•ผ, ์†”์งํžˆ ๋งํ•ด์„œ ํ”„๋กœ๊ทธ๋žจ ๋งŒ๋“ค๋‹ค ๋ณด๋ฉด ๋‹ต๋‹ตํ•  ๋•Œ ์žˆ์ž–์•„? ๐Ÿ˜ค ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๋˜‘๊ฐ™์€ ๋ฐ์ดํ„ฐ๋ฅผ ๊ณ„์† ๋ถˆ๋Ÿฌ์˜ค๋Š”๋ฐ ์™œ ์ด๋ ‡๊ฒŒ ๋А๋ฆฐ ๊ฑด์ง€... ์‚ฌ์šฉ์ž๋Š” ๋นจ๋ฆฌ๋นจ๋ฆฌ ๋ณด์—ฌ๋‹ฌ๋ผ๊ณ  ๋‚œ๋ฆฌ๊ณ , ์„œ๋ฒ„๋Š” ํ—‰ํ—‰๊ฑฐ๋ฆฌ๊ณ . ์ด๋Ÿด ๋•Œ ํ•„์š”ํ•œ ๊ฒŒ ๋ฐ”๋กœ ์บ์‹ฑ(Caching)์ด์•ผ!
๐Ÿ’ก ์บ์‹ฑ์ด๋ž€? ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋น ๋ฅด๊ฒŒ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ์ž„์‹œ ์ €์žฅ์†Œ์— ๋ณด๊ด€ํ•ด๋‘๋Š” ๊ธฐ๋ฒ•์ด์•ผ. ๋งˆ์น˜ ์ž์ฃผ ์“ฐ๋Š” ๋ฌผ๊ฑด์„ ์ฑ…์ƒ ์œ„์— ์˜ฌ๋ ค๋‘๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ๋ง์ด์ง€. ๋งค๋ฒˆ ์ฐฝ๊ณ (๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค)๊นŒ์ง€ ๊ฐ€์ง€ ์•Š์•„๋„ ๋˜๋‹ˆ๊นŒ ์—„์ฒญ ๋น ๋ฅด์ง€!
์ƒ๊ฐํ•ด๋ด. ๋„ค๊ฐ€ ์‡ผํ•‘๋ชฐ ์•ฑ์„ ๋งŒ๋“ค์—ˆ๋Š”๋ฐ, ๋ฉ”์ธ ํŽ˜์ด์ง€์— ๋ณด์—ฌ์ค„ ์ธ๊ธฐ ์ƒํ’ˆ ๋ชฉ๋ก์ด ์žˆ๋‹ค๊ณ  ์น˜์ž. ์ด ๋ชฉ๋ก์€ ํ•˜๋ฃจ์— ํ•œ๋‘ ๋ฒˆ ์ •๋„๋งŒ ๋ฐ”๋€Œ๋Š”๋ฐ, ์‚ฌ์šฉ์ž๊ฐ€ ์ ‘์†ํ•  ๋•Œ๋งˆ๋‹ค ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์กฐํšŒํ•œ๋‹ค๋ฉด? ๐Ÿค” - ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ถ€ํ•˜ ์ฆ๊ฐ€ ๐Ÿ“ˆ - ์‘๋‹ต ์†๋„ ๋А๋ ค์ง ๐ŸŒ - ์„œ๋ฒ„ ๋น„์šฉ ์ฆ๊ฐ€ ๐Ÿ’ธ - ์‚ฌ์šฉ์ž ๊ฒฝํ—˜ ์•…ํ™” ๐Ÿ˜ž ์ด๋Ÿฐ ๋ฌธ์ œ๋“ค์„ ์บ์‹ฑ์œผ๋กœ ํ•œ ๋ฐฉ์— ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์–ด! ์ฒซ ๋ฒˆ์งธ ์กฐํšŒ ๋•Œ๋งŒ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๊ฐ€์ ธ์˜ค๊ณ , ๊ทธ ๋‹ค์Œ๋ถ€ํ„ฐ๋Š” ์บ์‹œ์—์„œ ๋ฐ”๋กœ ๊บผ๋‚ด ์“ฐ๋Š” ๊ฑฐ์ง€. ์†๋„๋Š” 10๋ฐฐ~100๋ฐฐ ๋นจ๋ผ์ง€๊ณ , ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ํ•œ์ˆจ ๋Œ๋ฆฌ๊ณ ! ๐Ÿ˜Ž
์บ์‹ฑ ์—†์ด ์‚ฌ์šฉ์ž ์„œ๋ฒ„ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋А๋ฆผ ๐ŸŒ ๋งค๋ฒˆ ์กฐํšŒ ์บ์‹ฑ ์ ์šฉ ์‚ฌ์šฉ์ž ์บ์‹œ ๋น ๋ฆ„ โšก ์„œ๋ฒ„ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ํ•„์š”ํ•  ๋•Œ๋งŒ
## ๐Ÿ”ฅ Redis vs Memcached: ๋ญ˜ ์„ ํƒํ•ด์•ผ ํ• ๊นŒ? ์บ์‹ฑ ์†”๋ฃจ์…˜ ์ค‘์—์„œ ๊ฐ€์žฅ ์œ ๋ช…ํ•œ ๋‘ ์นœ๊ตฌ๊ฐ€ ์žˆ์–ด. ๋ฐ”๋กœ **Redis**์™€ **Memcached**! ๋‘˜ ๋‹ค ์ธ๋ฉ”๋ชจ๋ฆฌ(In-Memory) ๋ฐ์ดํ„ฐ ์ €์žฅ์†Œ์ธ๋ฐ, ๊ฐ์ž ํŠน์ง•์ด ๋‹ฌ๋ผ. ์นœ๊ตฌ ๋”ฐ๋ผ ๊ฐ•๋‚จ ๊ฐ€๋“ฏ์ด ๋ฌด์ž‘์ • ์„ ํƒํ•˜๋ฉด ์•ˆ ๋ผ! ๐Ÿ˜… ### ๐Ÿ“Š Redis์™€ Memcached ๋น„๊ตํ‘œ
ํŠน์ง• Redis ๐Ÿ”ด Memcached ๐ŸŸข
๋ฐ์ดํ„ฐ ํƒ€์ž… String, List, Set, Hash, Sorted Set ๋“ฑ ๋‹ค์–‘ String๋งŒ ์ง€์›
์˜์†์„ฑ ๋””์Šคํฌ ์ €์žฅ ๊ฐ€๋Šฅ (RDB, AOF) ๋ฉ”๋ชจ๋ฆฌ๋งŒ ์‚ฌ์šฉ (์žฌ์‹œ์ž‘ ์‹œ ๋ฐ์ดํ„ฐ ์†Œ์‹ค)
๋ณต์ œ Master-Slave ๋ณต์ œ ์ง€์› ๋ณต์ œ ๊ธฐ๋Šฅ ์—†์Œ
ํŠธ๋žœ์žญ์…˜ ์ง€์› ๋ฏธ์ง€์›
Pub/Sub ์ง€์› ๋ฏธ์ง€์›
๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ ๋ณดํ†ต ์šฐ์ˆ˜
์†๋„ ๋งค์šฐ ๋น ๋ฆ„ ์•ฝ๊ฐ„ ๋” ๋น ๋ฆ„
๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ์‹ฑ๊ธ€์Šค๋ ˆ๋“œ (6.0๋ถ€ํ„ฐ ์ผ๋ถ€ ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ) ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ
### ๐Ÿค” ๊ทธ๋ž˜์„œ ๋ญ˜ ์จ์•ผ ํ•ด?
โœ… Redis๋ฅผ ์„ ํƒํ•ด์•ผ ํ•  ๋•Œ โ€ข ๋‹ค์–‘ํ•œ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๊ฐ€ ํ•„์š”ํ•  ๋•Œ (๋ฆฌ์ŠคํŠธ, ์…‹, ํ•ด์‹œ ๋“ฑ) ๐Ÿ“ฆ
โ€ข ๋ฐ์ดํ„ฐ ์˜์†์„ฑ์ด ์ค‘์š”ํ•  ๋•Œ ๐Ÿ’พ
โ€ข ์‹ค์‹œ๊ฐ„ ์ˆœ์œ„ํ‘œ, ์ฑ„ํŒ… ๊ฐ™์€ ๋ณต์žกํ•œ ๊ธฐ๋Šฅ์ด ํ•„์š”ํ•  ๋•Œ ๐ŸŽฎ
โ€ข ๋ถ„์‚ฐ ๋ฝ(Lock)์ด๋‚˜ ์„ธ์…˜ ๊ด€๋ฆฌ๊ฐ€ ํ•„์š”ํ•  ๋•Œ ๐Ÿ”
โ€ข Pub/Sub ๋ฉ”์‹œ์ง• ํŒจํ„ด์„ ์‚ฌ์šฉํ•  ๋•Œ ๐Ÿ“ข
โœ… Memcached๋ฅผ ์„ ํƒํ•ด์•ผ ํ•  ๋•Œ โ€ข ๋‹จ์ˆœํ•œ ํ‚ค-๊ฐ’ ์ €์žฅ๋งŒ ํ•„์š”ํ•  ๋•Œ ๐Ÿ—๏ธ
โ€ข ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์ด ์ตœ์šฐ์„ ์ผ ๋•Œ ๐Ÿ’ช
โ€ข ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ ํ™˜๊ฒฝ์—์„œ ์ตœ๋Œ€ ์„ฑ๋Šฅ์ด ํ•„์š”ํ•  ๋•Œ โšก
โ€ข ๋ฐ์ดํ„ฐ ์œ ์‹ค์ด ํฌ๊ฒŒ ๋ฌธ์ œ๋˜์ง€ ์•Š์„ ๋•Œ ๐Ÿคท
โ€ข ์„ค์ •๊ณผ ์šด์˜์ด ๋‹จ์ˆœํ•ด์•ผ ํ•  ๋•Œ ๐ŸŽฏ
๋‚ด ๊ฒฝํ—˜์ƒ ์š”์ฆ˜์€ **Redis**๋ฅผ ๋” ๋งŽ์ด ์“ฐ๋Š” ์ถ”์„ธ์•ผ. ์™œ๋ƒํ•˜๋ฉด ๊ธฐ๋Šฅ์ด ํ›จ์”ฌ ํ’๋ถ€ํ•˜๊ฑฐ๋“ ! Memcached๋Š” ์ •๋ง ๋‹จ์ˆœํ•œ ์บ์‹ฑ๋งŒ ํ•„์š”ํ•  ๋•Œ ์“ฐ๋ฉด ์ข‹์•„. ๋งˆ์น˜ ์Šค์œ„์Šค ์•„๋ฏธ ๋‚˜์ดํ”„(Redis) vs ์ผ๋ฐ˜ ์นผ(Memcached) ๊ฐ™์€ ๋А๋‚Œ? ๐Ÿ”ช
## ๐Ÿ› ๏ธ Redis ์„ค์น˜ํ•˜๊ณ  ์‹œ์ž‘ํ•˜๊ธฐ ์ž, ์ด์ œ ๋ณธ๊ฒฉ์ ์œผ๋กœ Redis๋ฅผ ์„ค์น˜ํ•ด๋ณด์ž! ์šด์˜์ฒด์ œ๋ณ„๋กœ ๋ฐฉ๋ฒ•์ด ์กฐ๊ธˆ์”ฉ ๋‹ค๋ฅธ๋ฐ, ํ•˜๋‚˜์”ฉ ์•Œ๋ ค์ค„๊ฒŒ. ๐Ÿ˜Š ### ๐Ÿง Linux (Ubuntu/Debian)
# Redis ์„ค์น˜
sudo apt update
sudo apt install redis-server

# Redis ์„œ๋น„์Šค ์‹œ์ž‘
sudo systemctl start redis-server

# ๋ถ€ํŒ… ์‹œ ์ž๋™ ์‹œ์ž‘ ์„ค์ •
sudo systemctl enable redis-server

# Redis ์ ‘์† ํ…Œ์ŠคํŠธ
redis-cli ping
# ์‘๋‹ต: PONG (์ด๋ ‡๊ฒŒ ๋‚˜์˜ค๋ฉด ์„ฑ๊ณต!)
### ๐ŸŽ macOS
# Homebrew๋กœ ์„ค์น˜
brew install redis

# Redis ์„œ๋น„์Šค ์‹œ์ž‘
brew services start redis

# Redis ์ ‘์† ํ…Œ์ŠคํŠธ
redis-cli ping
### ๐ŸชŸ Windows Windows๋Š” ๊ณต์‹ ์ง€์›์ด ์•ˆ ๋˜์ง€๋งŒ, WSL(Windows Subsystem for Linux)์„ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ Docker๋ฅผ ์“ฐ๋ฉด ๋ผ! Docker๊ฐ€ ์ œ์ผ ํŽธํ•ด:
# Docker๋กœ Redis ์‹คํ–‰
docker run --name my-redis -p 6379:6379 -d redis

# Redis ์ ‘์†
docker exec -it my-redis redis-cli
๐ŸŽ“ Redis CLI ๊ธฐ๋ณธ ๋ช…๋ น์–ด SET key value - ๋ฐ์ดํ„ฐ ์ €์žฅ
GET key - ๋ฐ์ดํ„ฐ ์กฐํšŒ
DEL key - ๋ฐ์ดํ„ฐ ์‚ญ์ œ
EXISTS key - ํ‚ค ์กด์žฌ ํ™•์ธ
EXPIRE key seconds - ๋งŒ๋ฃŒ ์‹œ๊ฐ„ ์„ค์ •
TTL key - ๋‚จ์€ ๋งŒ๋ฃŒ ์‹œ๊ฐ„ ํ™•์ธ
KEYS pattern - ํŒจํ„ด์œผ๋กœ ํ‚ค ๊ฒ€์ƒ‰ (์šด์˜์—์„  ์ฃผ์˜!)
FLUSHALL - ๋ชจ๋“  ๋ฐ์ดํ„ฐ ์‚ญ์ œ (์กฐ์‹ฌ!)
### ๐Ÿงช Redis ๊ฐ„๋‹จ ํ…Œ์ŠคํŠธ ์„ค์น˜ํ–ˆ์œผ๋ฉด ํ•œ๋ฒˆ ํ…Œ์ŠคํŠธํ•ด๋ณด์ž! ํ„ฐ๋ฏธ๋„์—์„œ redis-cli๋ฅผ ์‹คํ–‰ํ•˜๊ณ :
# ๋ฌธ์ž์—ด ์ €์žฅ
SET myname "ํ™๊ธธ๋™"
# ์‘๋‹ต: OK

# ๋ฌธ์ž์—ด ์กฐํšŒ
GET myname
# ์‘๋‹ต: "ํ™๊ธธ๋™"

# ์ˆซ์ž ์ฆ๊ฐ€ (์กฐํšŒ์ˆ˜ ์นด์šดํŒ… ๊ฐ™์€ ๊ฑฐ)
SET viewcount 0
INCR viewcount
INCR viewcount
GET viewcount
# ์‘๋‹ต: "2"

# ๋งŒ๋ฃŒ ์‹œ๊ฐ„ ์„ค์ • (10์ดˆ ํ›„ ์ž๋™ ์‚ญ์ œ)
SET tempdata "์ž„์‹œ๋ฐ์ดํ„ฐ" EX 10
TTL tempdata
# ์‘๋‹ต: ๋‚จ์€ ์ดˆ (9, 8, 7...)
์‰ฝ์ง€? ์ด๊ฒŒ Redis์˜ ๊ธฐ๋ณธ์ด์•ผ! ๐ŸŽ‰
## ๐Ÿ’ป ์‹ค์ „! ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด๋ณ„ Redis ์‚ฌ์šฉ๋ฒ• ์ด์ œ ์ง„์งœ ์ฝ”๋“œ๋กœ ๋“ค์–ด๊ฐ€๋ณด์ž! ๊ฐ ์–ธ์–ด๋ณ„๋กœ Redis๋ฅผ ์–ด๋–ป๊ฒŒ ์“ฐ๋Š”์ง€ ์•Œ๋ ค์ค„๊ฒŒ. ์žฌ๋Šฅ๋„ท์—์„œ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์žฌ๋Šฅ์„ ๊ณต์œ ํ•˜๋Š” ๋ถ„๋“ค๋„ ์ด๋Ÿฐ ๋‚ด์šฉ ๋งŽ์ด ๊ถ๊ธˆํ•ดํ•˜๋”๋ผ๊ณ ! ๐Ÿ˜„ ### ๐Ÿ Python์—์„œ Redis ์‚ฌ์šฉํ•˜๊ธฐ Python์€ redis-py ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ด. ์„ค์น˜๋ถ€ํ„ฐ ํ•ด๋ณด์ž:
# Redis ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์„ค์น˜
pip install redis
์ด์ œ ์ฝ”๋“œ ์ž‘์„ฑ! ์‹ค์ œ ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ์‚ฌ์šฉ์ž ์„ธ์…˜์„ ์บ์‹ฑํ•˜๋Š” ์˜ˆ์ œ์•ผ:
import redis
import json
from datetime import timedelta

# Redis ์—ฐ๊ฒฐ
r = redis.Redis(
    host='localhost',
    port=6379,
    db=0,
    decode_responses=True  # ๋ฌธ์ž์—ด๋กœ ์ž๋™ ๋””์ฝ”๋”ฉ
)

# 1. ๊ฐ„๋‹จํ•œ ์บ์‹ฑ ์˜ˆ์ œ
def get_user_profile(user_id):
    """์‚ฌ์šฉ์ž ํ”„๋กœํ•„ ์กฐํšŒ (์บ์‹ฑ ์ ์šฉ)"""
    
    # ์บ์‹œ ํ‚ค ์ƒ์„ฑ
    cache_key = f"user:profile:{user_id}"
    
    # ์บ์‹œ์—์„œ ๋จผ์ € ํ™•์ธ
    cached_data = r.get(cache_key)
    
    if cached_data:
        print("โœ… ์บ์‹œ์—์„œ ๊ฐ€์ ธ์˜ด!")
        return json.loads(cached_data)
    
    # ์บ์‹œ์— ์—†์œผ๋ฉด DB์—์„œ ์กฐํšŒ (๊ฐ€์ •)
    print("๐Ÿ“€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ์กฐํšŒ...")
    user_data = {
        "id": user_id,
        "name": "ํ™๊ธธ๋™",
        "email": "hong@example.com",
        "age": 25
    }
    
    # ์บ์‹œ์— ์ €์žฅ (1์‹œ๊ฐ„ ์œ ์ง€)
    r.setex(
        cache_key,
        timedelta(hours=1),
        json.dumps(user_data)
    )
    
    return user_data

# 2. ์กฐํšŒ์ˆ˜ ์นด์šดํŒ…
def increment_view_count(post_id):
    """๊ฒŒ์‹œ๊ธ€ ์กฐํšŒ์ˆ˜ ์ฆ๊ฐ€"""
    key = f"post:views:{post_id}"
    return r.incr(key)

# 3. ์ตœ๊ทผ ๋ณธ ์ƒํ’ˆ ๋ชฉ๋ก (๋ฆฌ์ŠคํŠธ ํ™œ์šฉ)
def add_recent_product(user_id, product_id):
    """์ตœ๊ทผ ๋ณธ ์ƒํ’ˆ ์ถ”๊ฐ€ (์ตœ๋Œ€ 10๊ฐœ ์œ ์ง€)"""
    key = f"user:recent:{user_id}"
    
    # ๋ฆฌ์ŠคํŠธ ์•ž์— ์ถ”๊ฐ€
    r.lpush(key, product_id)
    
    # 10๊ฐœ๋งŒ ์œ ์ง€ (๋‚˜๋จธ์ง€ ์‚ญ์ œ)
    r.ltrim(key, 0, 9)
    
    # 7์ผ ํ›„ ์ž๋™ ์‚ญ์ œ
    r.expire(key, timedelta(days=7))

def get_recent_products(user_id):
    """์ตœ๊ทผ ๋ณธ ์ƒํ’ˆ ์กฐํšŒ"""
    key = f"user:recent:{user_id}"
    return r.lrange(key, 0, -1)

# 4. ์ธ๊ธฐ ๊ฒ€์ƒ‰์–ด ์ˆœ์œ„ (Sorted Set ํ™œ์šฉ)
def add_search_keyword(keyword):
    """๊ฒ€์ƒ‰์–ด ์นด์šดํŒ…"""
    key = "search:ranking"
    r.zincrby(key, 1, keyword)

def get_top_keywords(limit=10):
    """์ธ๊ธฐ ๊ฒ€์ƒ‰์–ด Top N"""
    key = "search:ranking"
    # ์ ์ˆ˜ ๋†’์€ ์ˆœ์œผ๋กœ ์กฐํšŒ
    return r.zrevrange(key, 0, limit-1, withscores=True)

# ์‚ฌ์šฉ ์˜ˆ์ œ
if __name__ == "__main__":
    # ํ”„๋กœํ•„ ์กฐํšŒ (์ฒซ ๋ฒˆ์งธ๋Š” DB, ๋‘ ๋ฒˆ์งธ๋Š” ์บ์‹œ)
    print(get_user_profile(123))
    print(get_user_profile(123))
    
    # ์กฐํšŒ์ˆ˜ ์ฆ๊ฐ€
    views = increment_view_count(456)
    print(f"ํ˜„์žฌ ์กฐํšŒ์ˆ˜: {views}")
    
    # ์ตœ๊ทผ ๋ณธ ์ƒํ’ˆ
    add_recent_product(123, "product_001")
    add_recent_product(123, "product_002")
    print(f"์ตœ๊ทผ ๋ณธ ์ƒํ’ˆ: {get_recent_products(123)}")
    
    # ์ธ๊ธฐ ๊ฒ€์ƒ‰์–ด
    add_search_keyword("Redis")
    add_search_keyword("Python")
    add_search_keyword("Redis")
    print(f"์ธ๊ธฐ ๊ฒ€์ƒ‰์–ด: {get_top_keywords(5)}")
๐Ÿ’ก Python Redis ํŒ โ€ข decode_responses=True ์˜ต์…˜์„ ์ฃผ๋ฉด ๋ฐ”์ดํŠธ ๋Œ€์‹  ๋ฌธ์ž์—ด๋กœ ๋ฐ›์„ ์ˆ˜ ์žˆ์–ด!
โ€ข JSON ๋ฐ์ดํ„ฐ๋Š” json.dumps()๋กœ ์ง๋ ฌํ™”ํ•ด์„œ ์ €์žฅํ•˜๊ณ , json.loads()๋กœ ๋ณต์›ํ•ด
โ€ข ์—ฐ๊ฒฐ ํ’€์„ ์‚ฌ์šฉํ•˜๋ฉด ์„ฑ๋Šฅ์ด ๋” ์ข‹์•„์ ธ: redis.ConnectionPool()
โ€ข Pipeline์„ ์“ฐ๋ฉด ์—ฌ๋Ÿฌ ๋ช…๋ น์„ ํ•œ ๋ฒˆ์— ๋ณด๋‚ผ ์ˆ˜ ์žˆ์–ด (๋„คํŠธ์›Œํฌ ์™•๋ณต ๊ฐ์†Œ)
### โ˜• Java/Spring Boot์—์„œ Redis ์‚ฌ์šฉํ•˜๊ธฐ Java ์ง„์˜์—์„œ๋Š” Spring Data Redis๋ฅผ ๋งŽ์ด ์จ. ๋จผ์ € ์˜์กด์„ฑ ์ถ”๊ฐ€:
// build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    implementation 'org.springframework.boot:spring-boot-starter-cache'
}
์„ค์ • ํŒŒ์ผ ์ž‘์„ฑ:
// application.yml
spring:
  redis:
    host: localhost
    port: 6379
  cache:
    type: redis
    redis:
      time-to-live: 3600000  # 1์‹œ๊ฐ„ (๋ฐ€๋ฆฌ์ดˆ)
Redis ์„ค์ • ํด๋ž˜์Šค:
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig {
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory connectionFactory) {
        
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        
        // Key๋Š” String์œผ๋กœ ์ง๋ ฌํ™”
        template.setKeySerializer(new StringRedisSerializer());
        
        // Value๋Š” JSON์œผ๋กœ ์ง๋ ฌํ™”
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        return template;
    }
    
    @Bean
    public RedisCacheManager cacheManager(
            RedisConnectionFactory connectionFactory) {
        
        RedisCacheConfiguration config = RedisCacheConfiguration
            .defaultCacheConfig()
            .entryTtl(Duration.ofHours(1))  // 1์‹œ๊ฐ„ TTL
            .serializeKeysWith(
                RedisSerializationContext.SerializationPair
                    .fromSerializer(new StringRedisSerializer())
            )
            .serializeValuesWith(
                RedisSerializationContext.SerializationPair
                    .fromSerializer(new GenericJackson2JsonRedisSerializer())
            );
        
        return RedisCacheManager.builder(connectionFactory)
            .cacheDefaults(config)
            .build();
    }
}
์‹ค์ œ ์‚ฌ์šฉ ์˜ˆ์ œ:
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class ProductService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    // 1. ์–ด๋…ธํ…Œ์ด์…˜ ๊ธฐ๋ฐ˜ ์บ์‹ฑ (๊ฐ€์žฅ ๊ฐ„๋‹จ!)
    @Cacheable(value = "products", key = "#productId")
    public Product getProduct(Long productId) {
        // ์บ์‹œ์— ์—†์œผ๋ฉด ์ด ๋ฉ”์„œ๋“œ๊ฐ€ ์‹คํ–‰๋˜๊ณ ,
        // ๊ฒฐ๊ณผ๊ฐ€ ์ž๋™์œผ๋กœ ์บ์‹œ์— ์ €์žฅ๋จ
        System.out.println("DB์—์„œ ์กฐํšŒ: " + productId);
        return productRepository.findById(productId)
            .orElseThrow(() -> new RuntimeException("์ƒํ’ˆ ์—†์Œ"));
    }
    
    // ์บ์‹œ ์‚ญ์ œ
    @CacheEvict(value = "products", key = "#productId")
    public void updateProduct(Long productId, Product product) {
        productRepository.save(product);
    }
    
    // 2. RedisTemplate ์ง์ ‘ ์‚ฌ์šฉ
    public void addToCart(Long userId, Long productId) {
        String key = "cart:" + userId;
        
        // Set์— ์ƒํ’ˆ ์ถ”๊ฐ€
        redisTemplate.opsForSet().add(key, productId);
        
        // 7์ผ ํ›„ ์ž๋™ ์‚ญ์ œ
        redisTemplate.expire(key, 7, TimeUnit.DAYS);
    }
    
    public Set<Object> getCart(Long userId) {
        String key = "cart:" + userId;
        return redisTemplate.opsForSet().members(key);
    }
    
    // 3. ์‹ค์‹œ๊ฐ„ ์žฌ๊ณ  ๊ด€๋ฆฌ
    public boolean decreaseStock(Long productId, int quantity) {
        String key = "stock:" + productId;
        
        // ์›์ž์  ์—ฐ์‚ฐ์œผ๋กœ ์žฌ๊ณ  ๊ฐ์†Œ
        Long remaining = redisTemplate.opsForValue()
            .decrement(key, quantity);
        
        if (remaining != null && remaining >= 0) {
            return true;  // ์žฌ๊ณ  ์ถฉ๋ถ„
        } else {
            // ์žฌ๊ณ  ๋ถ€์กฑ ์‹œ ๋กค๋ฐฑ
            redisTemplate.opsForValue().increment(key, quantity);
            return false;
        }
    }
    
    // 4. ๋ถ„์‚ฐ ๋ฝ ๊ตฌํ˜„
    public boolean acquireLock(String lockKey, long timeout) {
        String value = UUID.randomUUID().toString();
        
        Boolean success = redisTemplate.opsForValue()
            .setIfAbsent(lockKey, value, timeout, TimeUnit.SECONDS);
        
        return Boolean.TRUE.equals(success);
    }
    
    public void releaseLock(String lockKey) {
        redisTemplate.delete(lockKey);
    }
}
๐ŸŽฏ Spring Boot Redis ํ•ต์‹ฌ ํฌ์ธํŠธ โ€ข @Cacheable - ๋ฉ”์„œ๋“œ ๊ฒฐ๊ณผ๋ฅผ ์บ์‹ฑ (์กฐํšŒ)
โ€ข @CachePut - ์บ์‹œ ์—…๋ฐ์ดํŠธ (์ˆ˜์ •)
โ€ข @CacheEvict - ์บ์‹œ ์‚ญ์ œ
โ€ข RedisTemplate - ์ง์ ‘ Redis ์กฐ์ž‘
โ€ข ์ง๋ ฌํ™” ์„ค์ •์ด ์ค‘์š”ํ•ด! JSON ์ง๋ ฌํ™” ์ถ”์ฒœ
### ๐ŸŸจ Node.js์—์„œ Redis ์‚ฌ์šฉํ•˜๊ธฐ Node.js๋Š” ioredis ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๊ฐ€ ์ œ์ผ ์ข‹์•„. ์„ค์น˜:
# ioredis ์„ค์น˜
npm install ioredis
Express ์•ฑ์—์„œ Redis ์บ์‹ฑ ๋ฏธ๋“ค์›จ์–ด ๋งŒ๋“ค๊ธฐ:
const express = require('express');
const Redis = require('ioredis');

const app = express();
const redis = new Redis({
  host: 'localhost',
  port: 6379,
  retryStrategy: (times) => {
    const delay = Math.min(times * 50, 2000);
    return delay;
  }
});

// ์บ์‹ฑ ๋ฏธ๋“ค์›จ์–ด
function cacheMiddleware(duration) {
  return async (req, res, next) => {
    const key = `cache:${req.originalUrl}`;
    
    try {
      // ์บ์‹œ ํ™•์ธ
      const cached = await redis.get(key);
      
      if (cached) {
        console.log('โœ… ์บ์‹œ ํžˆํŠธ!');
        return res.json(JSON.parse(cached));
      }
      
      // ์บ์‹œ ๋ฏธ์Šค - ์›๋ž˜ ์‘๋‹ต ๊ฐ€๋กœ์ฑ„๊ธฐ
      res.originalJson = res.json;
      res.json = async (data) => {
        // ์‘๋‹ต ๋ฐ์ดํ„ฐ๋ฅผ ์บ์‹œ์— ์ €์žฅ
        await redis.setex(key, duration, JSON.stringify(data));
        res.originalJson(data);
      };
      
      next();
    } catch (error) {
      console.error('์บ์‹œ ์—๋Ÿฌ:', error);
      next();
    }
  };
}

// API ๋ผ์šฐํŠธ (์บ์‹ฑ ์ ์šฉ)
app.get('/api/products', cacheMiddleware(300), async (req, res) => {
  // ์‹ค์ œ๋กœ๋Š” DB ์กฐํšŒ
  console.log('๐Ÿ“€ DB์—์„œ ์กฐํšŒ...');
  
  const products = [
    { id: 1, name: '๋…ธํŠธ๋ถ', price: 1500000 },
    { id: 2, name: '๋งˆ์šฐ์Šค', price: 30000 },
    { id: 3, name: 'ํ‚ค๋ณด๋“œ', price: 80000 }
  ];
  
  // ์‘๋‹ต (์ž๋™์œผ๋กœ ์บ์‹œ๋จ)
  res.json(products);
});

// ์‹ค์‹œ๊ฐ„ ์ข‹์•„์š” ์นด์šดํŒ…
app.post('/api/posts/:id/like', async (req, res) => {
  const postId = req.params.id;
  const key = `post:likes:${postId}`;
  
  // ์ข‹์•„์š” ์ˆ˜ ์ฆ๊ฐ€
  const likes = await redis.incr(key);
  
  res.json({ postId, likes });
});

// ์˜จ๋ผ์ธ ์‚ฌ์šฉ์ž ์ˆ˜ (Set ํ™œ์šฉ)
app.post('/api/users/:id/online', async (req, res) => {
  const userId = req.params.id;
  const key = 'users:online';
  
  // Set์— ์‚ฌ์šฉ์ž ์ถ”๊ฐ€ (์ค‘๋ณต ์ž๋™ ์ œ๊ฑฐ)
  await redis.sadd(key, userId);
  
  // 5๋ถ„ ํ›„ ์ž๋™ ์ œ๊ฑฐ
  await redis.expire(`user:${userId}:online`, 300);
  
  // ํ˜„์žฌ ์˜จ๋ผ์ธ ์‚ฌ์šฉ์ž ์ˆ˜
  const count = await redis.scard(key);
  
  res.json({ onlineUsers: count });
});

// ์‹ค์‹œ๊ฐ„ ์ฑ„ํŒ… (Pub/Sub)
const subscriber = new Redis();
const publisher = new Redis();

subscriber.subscribe('chat:room1');

subscriber.on('message', (channel, message) => {
  console.log(`[${channel}] ${message}`);
  // WebSocket์œผ๋กœ ํด๋ผ์ด์–ธํŠธ์—๊ฒŒ ์ „์†ก
});

app.post('/api/chat/send', async (req, res) => {
  const { message } = req.body;
  
  // ๋ฉ”์‹œ์ง€ ๋ฐœํ–‰
  await publisher.publish('chat:room1', message);
  
  res.json({ success: true });
});

// ์„ธ์…˜ ์ €์žฅ์†Œ๋กœ Redis ์‚ฌ์šฉ
const session = require('express-session');
const RedisStore = require('connect-redis')(session);

app.use(session({
  store: new RedisStore({ client: redis }),
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 1000 * 60 * 60 * 24  // 1์ผ
  }
}));

app.listen(3000, () => {
  console.log('์„œ๋ฒ„ ์‹œ์ž‘: http://localhost:3000');
});
โš ๏ธ Node.js Redis ์ฃผ์˜์‚ฌํ•ญ โ€ข Redis ์—ฐ๊ฒฐ์€ ์‹ฑ๊ธ€ํ†ค์œผ๋กœ ๊ด€๋ฆฌํ•ด์•ผ ํ•ด (๋งค๋ฒˆ ์ƒˆ๋กœ ์—ฐ๊ฒฐํ•˜๋ฉด ์•ˆ ๋ผ!)
โ€ข async/await๋ฅผ ๊ผญ ์‚ฌ์šฉํ•ด (์ฝœ๋ฐฑ ์ง€์˜ฅ ๋ฐฉ์ง€)
โ€ข ์—๋Ÿฌ ํ•ธ๋“ค๋ง ํ•„์ˆ˜! Redis ์„œ๋ฒ„๊ฐ€ ๋‹ค์šด๋˜๋ฉด ์•ฑ์ด ๋ฉˆ์ถœ ์ˆ˜ ์žˆ์–ด
โ€ข Pub/Sub ์‚ฌ์šฉ ์‹œ ๊ตฌ๋…์ž์™€ ๋ฐœํ–‰์ž๋Š” ๋ณ„๋„ ์—ฐ๊ฒฐ ํ•„์š”
## ๐ŸŽจ Memcached ์‚ฌ์šฉ๋ฒ• Redis๋งŒํผ ํ™”๋ คํ•˜์ง„ ์•Š์ง€๋งŒ, Memcached๋„ ์•Œ์•„๋‘๋ฉด ์ข‹์•„! ์„ค์น˜๋ถ€ํ„ฐ ํ•ด๋ณด์ž. ### ๐Ÿ“ฆ Memcached ์„ค์น˜
# Ubuntu/Debian
sudo apt install memcached

# macOS
brew install memcached

# ์„œ๋น„์Šค ์‹œ์ž‘
sudo systemctl start memcached  # Linux
brew services start memcached   # macOS

# Docker
docker run -d -p 11211:11211 --name my-memcached memcached
### ๐Ÿ Python์—์„œ Memcached ์‚ฌ์šฉ
# pymemcache ์„ค์น˜
pip install pymemcache

# ์ฝ”๋“œ ์˜ˆ์ œ
from pymemcache.client import base

# Memcached ์—ฐ๊ฒฐ
client = base.Client(('localhost', 11211))

# ๋ฐ์ดํ„ฐ ์ €์žฅ (60์ดˆ TTL)
client.set('user:123', b'{"name":"ํ™๊ธธ๋™","age":25}', expire=60)

# ๋ฐ์ดํ„ฐ ์กฐํšŒ
data = client.get('user:123')
print(data)  # b'{"name":"ํ™๊ธธ๋™","age":25}'

# ๋ฐ์ดํ„ฐ ์‚ญ์ œ
client.delete('user:123')

# ์ˆซ์ž ์ฆ๊ฐ€
client.set('counter', 0)
client.incr('counter', 1)  # 1 ์ฆ๊ฐ€
print(client.get('counter'))  # b'1'

# ์—ฌ๋Ÿฌ ํ‚ค ํ•œ ๋ฒˆ์— ์กฐํšŒ
client.set_multi({
    'key1': b'value1',
    'key2': b'value2',
    'key3': b'value3'
}, expire=300)

results = client.get_multi(['key1', 'key2', 'key3'])
print(results)

# ์—ฐ๊ฒฐ ์ข…๋ฃŒ
client.close()
### โ˜• Java์—์„œ Memcached ์‚ฌ์šฉ
// build.gradle
dependencies {
    implementation 'com.googlecode.xmemcached:xmemcached:2.4.7'
}

// Java ์ฝ”๋“œ
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;

public class MemcachedExample {
    
    public static void main(String[] args) throws Exception {
        // Memcached ์—ฐ๊ฒฐ
        MemcachedClientBuilder builder = 
            new XMemcachedClientBuilder("localhost:11211");
        MemcachedClient client = builder.build();
        
        try {
            // ๋ฐ์ดํ„ฐ ์ €์žฅ (60์ดˆ TTL)
            client.set("user:123", 60, "ํ™๊ธธ๋™");
            
            // ๋ฐ์ดํ„ฐ ์กฐํšŒ
            String name = client.get("user:123");
            System.out.println("์ด๋ฆ„: " + name);
            
            // ์ˆซ์ž ์ฆ๊ฐ€
            client.set("viewcount", 0, 0);
            client.incr("viewcount", 1);
            
            Long count = client.get("viewcount");
            System.out.println("์กฐํšŒ์ˆ˜: " + count);
            
            // CAS (Compare-And-Swap) ์—ฐ์‚ฐ
            client.cas("user:123", 60, "๊น€์ฒ ์ˆ˜");
            
        } finally {
            client.shutdown();
        }
    }
}
๐Ÿ” Memcached vs Redis ์‹ค์ „ ์„ ํƒ ๊ฐ€์ด๋“œ Memcached๊ฐ€ ๋” ๋‚˜์€ ๊ฒฝ์šฐ:
โ€ข ๋‹จ์ˆœ ๋ฌธ์ž์—ด ์บ์‹ฑ๋งŒ ํ•„์š” (HTML ์กฐ๊ฐ, API ์‘๋‹ต ๋“ฑ)
โ€ข ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ์ œํ•œ์ ์ด๊ณ  ํšจ์œจ์ด ์ค‘์š”
โ€ข ๋ฉ€ํ‹ฐ์ฝ”์–ด CPU๋ฅผ ์ตœ๋Œ€ํ•œ ํ™œ์šฉํ•˜๊ณ  ์‹ถ์„ ๋•Œ

Redis๊ฐ€ ๋” ๋‚˜์€ ๊ฒฝ์šฐ:
โ€ข ๋ฆฌ์ŠคํŠธ, ์…‹, ํ•ด์‹œ ๊ฐ™์€ ๋ณต์žกํ•œ ์ž๋ฃŒ๊ตฌ์กฐ ํ•„์š”
โ€ข ๋ฐ์ดํ„ฐ ์˜์†์„ฑ์ด ํ•„์š” (์„œ๋ฒ„ ์žฌ์‹œ์ž‘ ํ›„์—๋„ ์œ ์ง€)
โ€ข ์‹ค์‹œ๊ฐ„ ์ˆœ์œ„ํ‘œ, ์ฑ„ํŒ…, ์„ธ์…˜ ๊ด€๋ฆฌ ๋“ฑ
โ€ข ๋ถ„์‚ฐ ๋ฝ, Pub/Sub ๊ฐ™์€ ๊ณ ๊ธ‰ ๊ธฐ๋Šฅ ํ•„์š”
์บ์‹ฑ ์ „๋žต ํŒจํ„ด Cache-Aside ๊ฐ€์žฅ ์ผ๋ฐ˜์ ์ธ ํŒจํ„ด 1. ์บ์‹œ ํ™•์ธ 2. ์—†์œผ๋ฉด DB ์กฐํšŒ 3. ์บ์‹œ์— ์ €์žฅ 4. ๋ฐ์ดํ„ฐ ๋ฐ˜ํ™˜ Write-Through ์“ฐ๊ธฐ ์‹œ ์บ์‹œ๋„ ์—…๋ฐ์ดํŠธ 1. DB์— ์“ฐ๊ธฐ 2. ์บ์‹œ์—๋„ ์“ฐ๊ธฐ 3. ์ผ๊ด€์„ฑ ๋ณด์žฅ 4. ์“ฐ๊ธฐ ์ง€์—ฐ ๋ฐœ์ƒ Write-Behind ๋น„๋™๊ธฐ ์“ฐ๊ธฐ 1. ์บ์‹œ์—๋งŒ ์“ฐ๊ธฐ 2. ์ฆ‰์‹œ ์‘๋‹ต 3. ๋‚˜์ค‘์— DB ๋ฐ˜์˜ 4. ๋น ๋ฅด์ง€๋งŒ ์œ„ํ—˜ Read-Through ์บ์‹œ๊ฐ€ DB ์กฐํšŒ ๋‹ด๋‹น 1. ์บ์‹œ์— ์š”์ฒญ 2. ์บ์‹œ๊ฐ€ DB ์กฐํšŒ 3. ์บ์‹œ๊ฐ€ ์ €์žฅ 4. ๋ฐ์ดํ„ฐ ๋ฐ˜ํ™˜ Refresh-Ahead ๋งŒ๋ฃŒ ์ „ ๋ฏธ๋ฆฌ ๊ฐฑ์‹  1. TTL ๋ชจ๋‹ˆํ„ฐ๋ง 2. ๋งŒ๋ฃŒ ์ „ ๊ฐฑ์‹  3. ํ•ญ์ƒ ์ตœ์‹  ์œ ์ง€ 4. ๋ณต์žก๋„ ์ฆ๊ฐ€
## ๐ŸŽฏ ์บ์‹ฑ ์ „๋žต ํŒจํ„ด ์ƒ์„ธ ์„ค๋ช… ์œ„ ๊ทธ๋ฆผ์—์„œ ๋ณธ 5๊ฐ€์ง€ ํŒจํ„ด์„ ์‹ค์ œ ์ฝ”๋“œ๋กœ ๊ตฌํ˜„ํ•ด๋ณด์ž! ๊ฐ ํŒจํ„ด๋งˆ๋‹ค ์žฅ๋‹จ์ ์ด ์žˆ์œผ๋‹ˆ ์ƒํ™ฉ์— ๋งž๊ฒŒ ์„ ํƒํ•ด์•ผ ํ•ด. ๐Ÿ˜Š ### 1๏ธโƒฃ Cache-Aside (Lazy Loading) ๊ฐ€์žฅ ๋งŽ์ด ์“ฐ๋Š” ํŒจํ„ด์ด์•ผ! ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์บ์‹œ๋ฅผ ์ง์ ‘ ๊ด€๋ฆฌํ•ด.
// Python ์˜ˆ์ œ
import redis
import json

r = redis.Redis(decode_responses=True)

def get_product_cache_aside(product_id):
    """Cache-Aside ํŒจํ„ด"""
    cache_key = f"product:{product_id}"
    
    # 1. ์บ์‹œ ํ™•์ธ
    cached = r.get(cache_key)
    if cached:
        print("โœ… ์บ์‹œ ํžˆํŠธ!")
        return json.loads(cached)
    
    # 2. ์บ์‹œ ๋ฏธ์Šค - DB ์กฐํšŒ
    print("๐Ÿ“€ ์บ์‹œ ๋ฏธ์Šค - DB ์กฐํšŒ")
    product = db.query(f"SELECT * FROM products WHERE id = {product_id}")
    
    # 3. ์บ์‹œ์— ์ €์žฅ
    r.setex(cache_key, 3600, json.dumps(product))
    
    return product

def update_product_cache_aside(product_id, data):
    """์—…๋ฐ์ดํŠธ ์‹œ ์บ์‹œ ๋ฌดํšจํ™”"""
    # DB ์—…๋ฐ์ดํŠธ
    db.update(product_id, data)
    
    # ์บ์‹œ ์‚ญ์ œ (๋‹ค์Œ ์กฐํšŒ ์‹œ ์ƒˆ๋กœ ๋กœ๋“œ๋จ)
    r.delete(f"product:{product_id}")
โœ… Cache-Aside ์žฅ์  โ€ข ๊ตฌํ˜„์ด ๊ฐ„๋‹จํ•˜๊ณ  ์ง๊ด€์ 
โ€ข ์บ์‹œ ์žฅ์•  ์‹œ์—๋„ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋™์ž‘ (DB๋กœ ํด๋ฐฑ)
โ€ข ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋งŒ ์บ์‹ฑ (๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์ )

โŒ Cache-Aside ๋‹จ์ 
โ€ข ์ฒซ ์š”์ฒญ์€ ํ•ญ์ƒ ๋А๋ฆผ (์บ์‹œ ๋ฏธ์Šค)
โ€ข ์บ์‹œ์™€ DB ๋ถˆ์ผ์น˜ ๊ฐ€๋Šฅ์„ฑ
โ€ข ์ฝ”๋“œ๊ฐ€ ๋ณต์žกํ•ด์งˆ ์ˆ˜ ์žˆ์Œ
### 2๏ธโƒฃ Write-Through ๋ฐ์ดํ„ฐ๋ฅผ ์“ธ ๋•Œ ์บ์‹œ์™€ DB๋ฅผ ๋™์‹œ์— ์—…๋ฐ์ดํŠธํ•˜๋Š” ํŒจํ„ด์ด์•ผ.
// Node.js ์˜ˆ์ œ
async function saveProductWriteThrough(productId, data) {
  const key = `product:${productId}`;
  
  try {
    // 1. DB์— ์ €์žฅ
    await db.products.update(productId, data);
    
    // 2. ์บ์‹œ์—๋„ ์ €์žฅ (๋™๊ธฐ์ ์œผ๋กœ)
    await redis.setex(key, 3600, JSON.stringify(data));
    
    console.log('โœ… DB์™€ ์บ์‹œ ๋ชจ๋‘ ์—…๋ฐ์ดํŠธ ์™„๋ฃŒ');
    return { success: true };
    
  } catch (error) {
    // ๋กค๋ฐฑ ์ฒ˜๋ฆฌ
    console.error('โŒ ์ €์žฅ ์‹คํŒจ:', error);
    throw error;
  }
}

async function getProductWriteThrough(productId) {
  const key = `product:${productId}`;
  
  // ์บ์‹œ์—์„œ ์กฐํšŒ (ํ•ญ์ƒ ์ตœ์‹  ๋ฐ์ดํ„ฐ)
  const cached = await redis.get(key);
  
  if (cached) {
    return JSON.parse(cached);
  }
  
  // ์บ์‹œ ๋ฏธ์Šค (๊ฑฐ์˜ ๋ฐœ์ƒ ์•ˆ ํ•จ)
  const product = await db.products.findById(productId);
  await redis.setex(key, 3600, JSON.stringify(product));
  
  return product;
}
โœ… Write-Through ์žฅ์  โ€ข ์บ์‹œ์™€ DB ์ผ๊ด€์„ฑ ๋ณด์žฅ
โ€ข ์ฝ๊ธฐ ์„ฑ๋Šฅ ์šฐ์ˆ˜ (ํ•ญ์ƒ ์บ์‹œ์— ์žˆ์Œ)
โ€ข ๋ฐ์ดํ„ฐ ์œ ์‹ค ์œ„ํ—˜ ๋‚ฎ์Œ

โŒ Write-Through ๋‹จ์ 
โ€ข ์“ฐ๊ธฐ ์„ฑ๋Šฅ ์ €ํ•˜ (๋‘ ๊ณณ์— ๋ชจ๋‘ ์จ์•ผ ํ•จ)
โ€ข ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฐ์ดํ„ฐ๋„ ์บ์‹ฑ (๋ฉ”๋ชจ๋ฆฌ ๋‚ญ๋น„)
โ€ข ๊ตฌํ˜„ ๋ณต์žก๋„ ์ฆ๊ฐ€
### 3๏ธโƒฃ Write-Behind (Write-Back) ์บ์‹œ์—๋งŒ ๋จผ์ € ์“ฐ๊ณ , ๋‚˜์ค‘์— ๋น„๋™๊ธฐ๋กœ DB์— ๋ฐ˜์˜ํ•˜๋Š” ํŒจํ„ด์ด์•ผ. ์„ฑ๋Šฅ์€ ์ตœ๊ณ ์ง€๋งŒ ์œ„ํ—˜ํ•ด! โš ๏ธ
// Python ์˜ˆ์ œ (Celery ์‚ฌ์šฉ)
from celery import Celery
import redis

app = Celery('tasks', broker='redis://localhost:6379/0')
r = redis.Redis(decode_responses=True)

@app.task
def sync_to_database(product_id, data):
    """๋น„๋™๊ธฐ๋กœ DB์— ์ €์žฅ"""
    try:
        db.products.update(product_id, data)
        print(f"โœ… DB ๋™๊ธฐํ™” ์™„๋ฃŒ: {product_id}")
    except Exception as e:
        print(f"โŒ DB ๋™๊ธฐํ™” ์‹คํŒจ: {e}")
        # ์žฌ์‹œ๋„ ๋กœ์ง ํ•„์š”

def save_product_write_behind(product_id, data):
    """Write-Behind ํŒจํ„ด"""
    key = f"product:{product_id}"
    
    # 1. ์บ์‹œ์—๋งŒ ์ €์žฅ (์ฆ‰์‹œ ์‘๋‹ต)
    r.setex(key, 3600, json.dumps(data))
    
    # 2. ๋น„๋™๊ธฐ ํƒœ์Šคํฌ๋กœ DB ์ €์žฅ ์˜ˆ์•ฝ
    sync_to_database.delay(product_id, data)
    
    print("โœ… ์บ์‹œ ์ €์žฅ ์™„๋ฃŒ (DB๋Š” ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ)")
    return {"success": True, "cached": True}

# ์ฃผ๊ธฐ์ ์œผ๋กœ ์บ์‹œ -> DB ๋™๊ธฐํ™”
@app.task
def periodic_sync():
    """5๋ถ„๋งˆ๋‹ค ๋ณ€๊ฒฝ๋œ ๋ฐ์ดํ„ฐ๋ฅผ DB์— ๋ฐ˜์˜"""
    dirty_keys = r.smembers("dirty:products")
    
    for key in dirty_keys:
        product_id = key.split(":")[1]
        data = r.get(f"product:{product_id}")
        
        if data:
            db.products.update(product_id, json.loads(data))
            r.srem("dirty:products", key)
โš ๏ธ Write-Behind ์ฃผ์˜์‚ฌํ•ญ โ€ข ์บ์‹œ ์„œ๋ฒ„ ์žฅ์•  ์‹œ ๋ฐ์ดํ„ฐ ์œ ์‹ค ๊ฐ€๋Šฅ!
โ€ข ๋ณต์žกํ•œ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํ•„์š”
โ€ข ์žฌ์‹œ๋„ ๋กœ์ง ํ•„์ˆ˜
โ€ข ๊ธˆ์œต ๊ฑฐ๋ž˜ ๊ฐ™์€ ์ค‘์š” ๋ฐ์ดํ„ฐ์—” ๋ถ€์ ํ•ฉ
โ€ข ๋กœ๊ทธ, ํ†ต๊ณ„ ๊ฐ™์€ ๋ฐ์ดํ„ฐ์— ์ ํ•ฉ
### 4๏ธโƒฃ Read-Through ์บ์‹œ๊ฐ€ DB ์กฐํšŒ๋ฅผ ๋Œ€์‹  ํ•ด์ฃผ๋Š” ํŒจํ„ด์ด์•ผ. ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์€ ์บ์‹œํ•˜๊ณ ๋งŒ ๋Œ€ํ™”ํ•ด!
// Java Spring ์˜ˆ์ œ
@Service
public class ProductCacheService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    private ProductRepository productRepository;
    
    public Product getProduct(Long productId) {
        String key = "product:" + productId;
        
        // ์บ์‹œ์— ์š”์ฒญ (์บ์‹œ๊ฐ€ ๋ชจ๋“  ๊ฑธ ์ฒ˜๋ฆฌ)
        return (Product) redisTemplate.execute(
            new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) {
                    byte[] keyBytes = key.getBytes();
                    byte[] value = connection.get(keyBytes);
                    
                    if (value != null) {
                        // ์บ์‹œ ํžˆํŠธ
                        return deserialize(value);
                    }
                    
                    // ์บ์‹œ ๋ฏธ์Šค - DB ์กฐํšŒ
                    Product product = productRepository
                        .findById(productId)
                        .orElseThrow();
                    
                    // ์บ์‹œ์— ์ €์žฅ
                    connection.setEx(
                        keyBytes,
                        3600,
                        serialize(product)
                    );
                    
                    return product;
                }
            }
        );
    }
}
### 5๏ธโƒฃ Refresh-Ahead ๋งŒ๋ฃŒ๋˜๊ธฐ ์ „์— ๋ฏธ๋ฆฌ ์บ์‹œ๋ฅผ ๊ฐฑ์‹ ํ•˜๋Š” ํŒจํ„ด์ด์•ผ. ํ•ญ์ƒ ์ตœ์‹  ๋ฐ์ดํ„ฐ๋ฅผ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ์–ด!
// Python ์˜ˆ์ œ
import redis
import threading
import time

r = redis.Redis(decode_responses=True)

class RefreshAheadCache:
    def __init__(self, ttl=3600, refresh_threshold=0.8):
        self.ttl = ttl
        self.refresh_threshold = refresh_threshold  # 80% ์ง€๋‚˜๋ฉด ๊ฐฑ์‹ 
        self.refresh_thread = None
        
    def get(self, key, loader_func):
        """๋ฐ์ดํ„ฐ ์กฐํšŒ (์ž๋™ ๊ฐฑ์‹ )"""
        cached = r.get(key)
        
        if cached:
            # TTL ํ™•์ธ
            remaining_ttl = r.ttl(key)
            threshold_time = self.ttl * self.refresh_threshold
            
            # ๋งŒ๋ฃŒ ์ž„๋ฐ• ์‹œ ๋ฐฑ๊ทธ๋ผ์šด๋“œ ๊ฐฑ์‹ 
            if remaining_ttl < threshold_time:
                self._refresh_async(key, loader_func)
            
            return json.loads(cached)
        
        # ์บ์‹œ ๋ฏธ์Šค
        data = loader_func()
        r.setex(key, self.ttl, json.dumps(data))
        return data
    
    def _refresh_async(self, key, loader_func):
        """๋น„๋™๊ธฐ๋กœ ์บ์‹œ ๊ฐฑ์‹ """
        def refresh():
            try:
                print(f"๐Ÿ”„ ์บ์‹œ ๊ฐฑ์‹  ์ค‘: {key}")
                data = loader_func()
                r.setex(key, self.ttl, json.dumps(data))
                print(f"โœ… ์บ์‹œ ๊ฐฑ์‹  ์™„๋ฃŒ: {key}")
            except Exception as e:
                print(f"โŒ ๊ฐฑ์‹  ์‹คํŒจ: {e}")
        
        thread = threading.Thread(target=refresh)
        thread.daemon = True
        thread.start()

# ์‚ฌ์šฉ ์˜ˆ์ œ
cache = RefreshAheadCache(ttl=3600, refresh_threshold=0.8)

def load_popular_products():
    """์ธ๊ธฐ ์ƒํ’ˆ ์กฐํšŒ (๋ฌด๊ฑฐ์šด ์ฟผ๋ฆฌ)"""
    time.sleep(2)  # DB ์กฐํšŒ ์‹œ๋ฎฌ๋ ˆ์ด์…˜
    return [
        {"id": 1, "name": "๋…ธํŠธ๋ถ", "sales": 1000},
        {"id": 2, "name": "๋งˆ์šฐ์Šค", "sales": 500}
    ]

# ์กฐํšŒ (TTL์˜ 80% ์ง€๋‚˜๋ฉด ์ž๋™ ๊ฐฑ์‹ )
products = cache.get("popular:products", load_popular_products)
๐Ÿ’ก Refresh-Ahead ํ™œ์šฉ ํŒ โ€ข ์ธ๊ธฐ ์ƒํ’ˆ, ๋ฒ ์ŠคํŠธ์…€๋Ÿฌ ๊ฐ™์€ ํ•ซํ•œ ๋ฐ์ดํ„ฐ์— ์ ํ•ฉ
โ€ข ์˜ˆ์ธก ๊ฐ€๋Šฅํ•œ ํŠธ๋ž˜ํ”ฝ ํŒจํ„ด์— ํšจ๊ณผ์ 
โ€ข ๊ฐฑ์‹  ๋น„์šฉ์ด ๋†’์€ ๋ฐ์ดํ„ฐ์— ์œ ์šฉ
โ€ข ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ž‘์—…์ด๋ฏ€๋กœ ์‚ฌ์šฉ์ž ๊ฒฝํ—˜ ํ–ฅ์ƒ
โ€ข ๋‹จ, ๋ชจ๋“  ๋ฐ์ดํ„ฐ์— ์ ์šฉํ•˜๋ฉด ๋ฆฌ์†Œ์Šค ๋‚ญ๋น„!
## ๐Ÿšจ ์บ์‹ฑ ์‚ฌ์šฉ ์‹œ ์ฃผ์˜์‚ฌํ•ญ๊ณผ ํ•จ์ • ์บ์‹ฑ์€ ๊ฐ•๋ ฅํ•˜์ง€๋งŒ, ์ž˜๋ชป ์“ฐ๋ฉด ๋…์ด ๋  ์ˆ˜ ์žˆ์–ด! ์‹ค์ „์—์„œ ์ž์ฃผ ๊ฒช๋Š” ๋ฌธ์ œ๋“ค์„ ์•Œ๋ ค์ค„๊ฒŒ. ๐Ÿ˜ฐ ### ๐Ÿ’ฅ 1. Cache Stampede (์บ์‹œ ์Šคํƒฌํ”ผ๋“œ) ์ธ๊ธฐ ์žˆ๋Š” ๋ฐ์ดํ„ฐ์˜ ์บ์‹œ๊ฐ€ ๋งŒ๋ฃŒ๋˜๋ฉด, ๋™์‹œ์— ์ˆ˜๋งŽ์€ ์š”์ฒญ์ด DB๋กœ ๋ชฐ๋ ค๊ฐ€๋Š” ํ˜„์ƒ์ด์•ผ!
// ๋ฌธ์ œ ์ƒํ™ฉ
async function getPopularProduct(productId) {
  const cached = await redis.get(`product:${productId}`);
  
  if (!cached) {
    // ๐Ÿ˜ฑ ๋™์‹œ์— 1000๋ช…์ด ์—ฌ๊ธฐ ๋„๋‹ฌํ•˜๋ฉด?
    // DB์— 1000๊ฐœ ์ฟผ๋ฆฌ๊ฐ€ ํ•œ๊บผ๋ฒˆ์—!
    const product = await db.query(`SELECT * FROM products WHERE id = ${productId}`);
    await redis.setex(`product:${productId}`, 3600, JSON.stringify(product));
    return product;
  }
  
  return JSON.parse(cached);
}

// ํ•ด๊ฒฐ์ฑ… 1: ๋ถ„์‚ฐ ๋ฝ ์‚ฌ์šฉ
const Redlock = require('redlock');
const redlock = new Redlock([redis]);

async function getPopularProductWithLock(productId) {
  const cacheKey = `product:${productId}`;
  const lockKey = `lock:${cacheKey}`;
  
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);
  
  try {
    // ๋ฝ ํš๋“ (10์ดˆ ํƒ€์ž„์•„์›ƒ)
    const lock = await redlock.lock(lockKey, 10000);
    
    try {
      // ๋‹ค์‹œ ํ•œ ๋ฒˆ ์บ์‹œ ํ™•์ธ (๋‹ค๋ฅธ ์Šค๋ ˆ๋“œ๊ฐ€ ์ด๋ฏธ ๋กœ๋“œํ–ˆ์„ ์ˆ˜๋„)
      const cached = await redis.get(cacheKey);
      if (cached) return JSON.parse(cached);
      
      // DB ์กฐํšŒ (ํ•œ ๋ฒˆ๋งŒ!)
      const product = await db.query(`SELECT * FROM products WHERE id = ${productId}`);
      await redis.setex(cacheKey, 3600, JSON.stringify(product));
      
      return product;
    } finally {
      await lock.unlock();
    }
  } catch (error) {
    // ๋ฝ ํš๋“ ์‹คํŒจ - ์ž ์‹œ ๋Œ€๊ธฐ ํ›„ ์žฌ์‹œ๋„
    await new Promise(resolve => setTimeout(resolve, 100));
    return getPopularProductWithLock(productId);
  }
}

// ํ•ด๊ฒฐ์ฑ… 2: Probabilistic Early Expiration (ํ™•๋ฅ ์  ์กฐ๊ธฐ ๋งŒ๋ฃŒ)
function getWithProbabilisticRefresh(key, ttl, loaderFunc) {
  const cached = r.get(key);
  
  if (cached) {
    const remainingTtl = r.ttl(key);
    const delta = Math.random() * ttl * 0.1;  // TTL์˜ 10% ๋žœ๋ค
    
    // ๋งŒ๋ฃŒ ์ž„๋ฐ• ์‹œ ํ™•๋ฅ ์ ์œผ๋กœ ๊ฐฑ์‹ 
    if (remainingTtl < delta) {
      // ๋น„๋™๊ธฐ๋กœ ๊ฐฑ์‹  (ํ˜„์žฌ ์บ์‹œ๋Š” ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜)
      refreshAsync(key, ttl, loaderFunc);
    }
    
    return JSON.parse(cached);
  }
  
  // ์บ์‹œ ๋ฏธ์Šค
  const data = loaderFunc();
  r.setex(key, ttl, JSON.dumps(data));
  return data;
}
### ๐Ÿ”„ 2. Cache Invalidation (์บ์‹œ ๋ฌดํšจํ™”) "์ปดํ“จํ„ฐ ๊ณผํ•™์—์„œ ์–ด๋ ค์šด ๊ฒƒ ๋‘ ๊ฐ€์ง€: ์บ์‹œ ๋ฌดํšจํ™”์™€ ์ด๋ฆ„ ์ง“๊ธฐ" ๋ผ๋Š” ์œ ๋ช…ํ•œ ๋ง์ด ์žˆ์–ด! ๐Ÿ˜…
# Python ์˜ˆ์ œ - ์—ฐ๊ด€ ์บ์‹œ ๋ฌดํšจํ™”

def update_product(product_id, data):
    """์ƒํ’ˆ ์—…๋ฐ์ดํŠธ ์‹œ ๊ด€๋ จ ์บ์‹œ ๋ชจ๋‘ ์‚ญ์ œ"""
    
    # DB ์—…๋ฐ์ดํŠธ
    db.products.update(product_id, data)
    
    # ๊ด€๋ จ ์บ์‹œ ํ‚ค๋“ค
    cache_keys = [
        f"product:{product_id}",                    # ์ƒํ’ˆ ์ƒ์„ธ
        f"product:list:category:{data['category']}", # ์นดํ…Œ๊ณ ๋ฆฌ ๋ชฉ๋ก
        "product:list:popular",                     # ์ธ๊ธฐ ์ƒํ’ˆ
        "product:list:new",                         # ์‹ ์ƒํ’ˆ
        f"search:results:{data['name']}"            # ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ
    ]
    
    # ๋ชจ๋‘ ์‚ญ์ œ
    for key in cache_keys:
        r.delete(key)
    
    print(f"โœ… {len(cache_keys)}๊ฐœ ์บ์‹œ ๋ฌดํšจํ™” ์™„๋ฃŒ")

# ํŒจํ„ด ๊ธฐ๋ฐ˜ ์‚ญ์ œ (์ฃผ์˜: ์šด์˜ ํ™˜๊ฒฝ์—์„œ๋Š” SCAN ์‚ฌ์šฉ!)
def invalidate_by_pattern(pattern):
    """ํŒจํ„ด์— ๋งž๋Š” ๋ชจ๋“  ์บ์‹œ ์‚ญ์ œ"""
    cursor = 0
    deleted = 0
    
    while True:
        cursor, keys = r.scan(cursor, match=pattern, count=100)
        
        if keys:
            r.delete(*keys)
            deleted += len(keys)
        
        if cursor == 0:
            break
    
    print(f"โœ… {deleted}๊ฐœ ์บ์‹œ ์‚ญ์ œ ์™„๋ฃŒ")

# ์‚ฌ์šฉ ์˜ˆ์ œ
invalidate_by_pattern("product:list:*")  # ๋ชจ๋“  ์ƒํ’ˆ ๋ชฉ๋ก ์บ์‹œ ์‚ญ์ œ
โš ๏ธ KEYS ๋ช…๋ น์–ด ์ ˆ๋Œ€ ์“ฐ์ง€ ๋งˆ! ์šด์˜ ํ™˜๊ฒฝ์—์„œ KEYS * ๊ฐ™์€ ๋ช…๋ น์–ด๋ฅผ ์“ฐ๋ฉด Redis๊ฐ€ ๋ฉˆ์ถฐ๋ฒ„๋ ค! ๋Œ€์‹  SCAN์„ ์‚ฌ์šฉํ•ด์•ผ ํ•ด. SCAN์€ ์ปค์„œ ๊ธฐ๋ฐ˜์œผ๋กœ ์กฐ๊ธˆ์”ฉ ์กฐํšŒํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์•ˆ์ „ํ•ด.
### ๐Ÿ˜ 3. Cache Penetration (์บ์‹œ ๊ด€ํ†ต) ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๊ณ„์† ์กฐํšŒํ•˜๋ฉด, ์บ์‹œ๋ฅผ ๋ฌด์‹œํ•˜๊ณ  ๋งค๋ฒˆ DB๋กœ ๊ฐ€๊ฒŒ ๋ผ!
// ๋ฌธ์ œ ์ƒํ™ฉ
async function getUser(userId) {
  const cached = await redis.get(`user:${userId}`);
  if (cached) return JSON.parse(cached);
  
  // ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์‚ฌ์šฉ์ž ID๋ฅผ ๊ณ„์† ์กฐํšŒํ•˜๋ฉด?
  // ๋งค๋ฒˆ DB ์ฟผ๋ฆฌ ๋ฐœ์ƒ! ๐Ÿ˜ฑ
  const user = await db.users.findById(userId);
  
  if (user) {
    await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
  }
  
  return user;
}

// ํ•ด๊ฒฐ์ฑ… 1: Null ๊ฐ’๋„ ์บ์‹ฑ
async function getUserWithNullCache(userId) {
  const cached = await redis.get(`user:${userId}`);
  
  if (cached !== null) {
    // "null" ๋ฌธ์ž์—ด์ด๋ฉด ์‹ค์ œ๋กœ ์—†๋Š” ๊ฒƒ
    return cached === "null" ? null : JSON.parse(cached);
  }
  
  const user = await db.users.findById(userId);
  
  if (user) {
    await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
  } else {
    // ์—†๋Š” ๋ฐ์ดํ„ฐ๋„ ์งง๊ฒŒ ์บ์‹ฑ (5๋ถ„)
    await redis.setex(`user:${userId}`, 300, "null");
  }
  
  return user;
}

// ํ•ด๊ฒฐ์ฑ… 2: Bloom Filter ์‚ฌ์šฉ
const BloomFilter = require('bloomfilter').BloomFilter;

// 1000๋งŒ ๊ฐœ ํ•ญ๋ชฉ, 0.01% ์˜คํƒ๋ฅ 
const bloom = new BloomFilter(10000000, 4);

// ์กด์žฌํ•˜๋Š” ์‚ฌ์šฉ์ž ID๋ฅผ Bloom Filter์— ์ถ”๊ฐ€
async function addUserToBloom(userId) {
  bloom.add(userId.toString());
}

async function getUserWithBloom(userId) {
  // Bloom Filter๋กœ ๋จผ์ € ํ™•์ธ
  if (!bloom.test(userId.toString())) {
    // ํ™•์‹คํžˆ ์—†์Œ!
    console.log("โŒ Bloom Filter: ์‚ฌ์šฉ์ž ์—†์Œ");
    return null;
  }
  
  // ์žˆ์„ ์ˆ˜๋„ ์žˆ์Œ - ์บ์‹œ/DB ํ™•์ธ
  const cached = await redis.get(`user:${userId}`);
  if (cached) return JSON.parse(cached);
  
  const user = await db.users.findById(userId);
  if (user) {
    await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
  }
  
  return user;
}
### ๐ŸŒŠ 4. Cache Avalanche (์บ์‹œ ๋ˆˆ์‚ฌํƒœ) ๋Œ€๋Ÿ‰์˜ ์บ์‹œ๊ฐ€ ๋™์‹œ์— ๋งŒ๋ฃŒ๋˜๋ฉด์„œ DB์— ์—„์ฒญ๋‚œ ๋ถ€ํ•˜๊ฐ€ ๊ฑธ๋ฆฌ๋Š” ํ˜„์ƒ!
# Python ์˜ˆ์ œ - TTL ๋ถ„์‚ฐ

import random

def set_with_jitter(key, data, base_ttl=3600):
    """TTL์— ๋žœ๋ค ์ง€ํ„ฐ ์ถ”๊ฐ€"""
    
    # ๊ธฐ๋ณธ TTL์˜ ยฑ10% ๋žœ๋ค
    jitter = random.randint(-int(base_ttl * 0.1), int(base_ttl * 0.1))
    actual_ttl = base_ttl + jitter
    
    r.setex(key, actual_ttl, json.dumps(data))
    print(f"โœ… TTL: {actual_ttl}์ดˆ (์ง€ํ„ฐ: {jitter}์ดˆ)")

# ๋Œ€๋Ÿ‰ ๋ฐ์ดํ„ฐ ์บ์‹ฑ ์‹œ
def cache_all_products():
    """๋ชจ๋“  ์ƒํ’ˆ ์บ์‹ฑ (TTL ๋ถ„์‚ฐ)"""
    products = db.products.all()
    
    for product in products:
        key = f"product:{product.id}"
        # ๊ฐ ์ƒํ’ˆ๋งˆ๋‹ค ๋‹ค๋ฅธ TTL (3240~3960์ดˆ)
        set_with_jitter(key, product, base_ttl=3600)

# ๊ณ„์ธต์  ๋งŒ๋ฃŒ ์‹œ๊ฐ„
def set_with_tiered_ttl(key, data, tier="hot"):
    """๋ฐ์ดํ„ฐ ์ค‘์š”๋„์— ๋”ฐ๋ผ TTL ์ฐจ๋“ฑ ์ ์šฉ"""
    
    ttl_map = {
        "hot": 7200,    # 2์‹œ๊ฐ„ (์ธ๊ธฐ ๋ฐ์ดํ„ฐ)
        "warm": 3600,   # 1์‹œ๊ฐ„ (์ผ๋ฐ˜ ๋ฐ์ดํ„ฐ)
        "cold": 1800    # 30๋ถ„ (๋น„์ธ๊ธฐ ๋ฐ์ดํ„ฐ)
    }
    
    base_ttl = ttl_map.get(tier, 3600)
    jitter = random.randint(0, int(base_ttl * 0.2))
    
    r.setex(key, base_ttl + jitter, json.dumps(data))
### ๐Ÿ” 5. ๋ณด์•ˆ ์ด์Šˆ ์บ์‹œ์— ๋ฏผ๊ฐํ•œ ์ •๋ณด๋ฅผ ์ €์žฅํ•  ๋•Œ ์กฐ์‹ฌํ•ด์•ผ ํ•ด!
// ์ž˜๋ชป๋œ ์˜ˆ
async function cacheUserData(userId) {
  const user = await db.users.findById(userId);
  
  // ๐Ÿ˜ฑ ๋น„๋ฐ€๋ฒˆํ˜ธ, ์นด๋“œ๋ฒˆํ˜ธ ๋“ฑ ๋ฏผ๊ฐ ์ •๋ณด๊นŒ์ง€ ์บ์‹ฑ!
  await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
}

// ์˜ฌ๋ฐ”๋ฅธ ์˜ˆ
async function cacheUserDataSafely(userId) {
  const user = await db.users.findById(userId);
  
  // ๋ฏผ๊ฐ ์ •๋ณด ์ œ๊ฑฐ
  const safeData = {
    id: user.id,
    name: user.name,
    email: user.email,
    // password, cardNumber ๋“ฑ์€ ์ œ์™ธ!
  };
  
  await redis.setex(`user:${userId}`, 3600, JSON.stringify(safeData));
}

// ์•”ํ˜ธํ™”ํ•ด์„œ ์ €์žฅ
const crypto = require('crypto');

function encrypt(text, key) {
  const cipher = crypto.createCipher('aes-256-cbc', key);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

function decrypt(encrypted, key) {
  const decipher = crypto.createDecipher('aes-256-cbc', key);
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

async function cacheWithEncryption(key, data, encryptionKey) {
  const encrypted = encrypt(JSON.stringify(data), encryptionKey);
  await redis.setex(key, 3600, encrypted);
}
## ๐Ÿ“Š ์บ์‹ฑ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง๊ณผ ์ตœ์ ํ™” ์บ์‹œ๋ฅผ ์ ์šฉํ–ˆ๋‹ค๊ณ  ๋์ด ์•„๋‹ˆ์•ผ! ์ œ๋Œ€๋กœ ์ž‘๋™ํ•˜๋Š”์ง€ ๋ชจ๋‹ˆํ„ฐ๋งํ•ด์•ผ ํ•ด. ๐Ÿ˜Ž ### ๐Ÿ“ˆ ํ•ต์‹ฌ ์ง€ํ‘œ (Key Metrics)
์ง€ํ‘œ ์„ค๋ช… ๋ชฉํ‘œ
Hit Rate ์บ์‹œ์—์„œ ์ฐพ์€ ๋น„์œจ 80% ์ด์ƒ
Miss Rate ์บ์‹œ์— ์—†์–ด์„œ DB ์กฐํšŒํ•œ ๋น„์œจ 20% ์ดํ•˜
Eviction Rate ๋ฉ”๋ชจ๋ฆฌ ๋ถ€์กฑ์œผ๋กœ ์‚ญ์ œ๋œ ๋น„์œจ ๋‚ฎ์„์ˆ˜๋ก ์ข‹์Œ
Latency ์บ์‹œ ์‘๋‹ต ์‹œ๊ฐ„ 1ms ์ดํ•˜
Memory Usage ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋ฅ  70~80%
Connection Count ๋™์‹œ ์—ฐ๊ฒฐ ์ˆ˜ ์ ์ ˆํžˆ ๊ด€๋ฆฌ
### ๐Ÿ” Redis ๋ชจ๋‹ˆํ„ฐ๋ง ์ฝ”๋“œ
# Python ์˜ˆ์ œ - ์บ์‹œ ํ†ต๊ณ„ ์ˆ˜์ง‘

import redis
import time
from datetime import datetime

class CacheMonitor:
    def __init__(self, redis_client):
        self.r = redis_client
        self.stats = {
            "hits": 0,
            "misses": 0,
            "total_requests": 0
        }
    
    def get_with_stats(self, key):
        """ํ†ต๊ณ„๋ฅผ ์ˆ˜์ง‘ํ•˜๋Š” get ๋ฉ”์„œ๋“œ"""
        self.stats["total_requests"] += 1
        
        cached = self.r.get(key)
        
        if cached:
            self.stats["hits"] += 1
            return cached
        else:
            self.stats["misses"] += 1
            return None
    
    def get_hit_rate(self):
        """์บ์‹œ ํžˆํŠธ์œจ ๊ณ„์‚ฐ"""
        if self.stats["total_requests"] == 0:
            return 0
        
        return (self.stats["hits"] / self.stats["total_requests"]) * 100
    
    def print_stats(self):
        """ํ†ต๊ณ„ ์ถœ๋ ฅ"""
        hit_rate = self.get_hit_rate()
        
        print("=" * 50)
        print(f"๐Ÿ“Š ์บ์‹œ ํ†ต๊ณ„ ({datetime.now()})")
        print("=" * 50)
        print(f"์ด ์š”์ฒญ: {self.stats['total_requests']}")
        print(f"ํžˆํŠธ: {self.stats['hits']}")
        print(f"๋ฏธ์Šค: {self.stats['misses']}")
        print(f"ํžˆํŠธ์œจ: {hit_rate:.2f}%")
        print("=" * 50)
    
    def get_redis_info(self):
        """Redis ์„œ๋ฒ„ ์ •๋ณด"""
        info = self.r.info()
        
        return {
            "version": info["redis_version"],
            "uptime_days": info["uptime_in_days"],
            "connected_clients": info["connected_clients"],
            "used_memory_human": info["used_memory_human"],
            "used_memory_peak_human": info["used_memory_peak_human"],
            "total_commands_processed": info["total_commands_processed"],
            "keyspace_hits": info.get("keyspace_hits", 0),
            "keyspace_misses": info.get("keyspace_misses", 0),
            "evicted_keys": info.get("evicted_keys", 0)
        }
    
    def calculate_hit_rate_from_redis(self):
        """Redis ๋‚ด๋ถ€ ํ†ต๊ณ„๋กœ ํžˆํŠธ์œจ ๊ณ„์‚ฐ"""
        info = self.r.info("stats")
        
        hits = info.get("keyspace_hits", 0)
        misses = info.get("keyspace_misses", 0)
        total = hits + misses
        
        if total == 0:
            return 0
        
        return (hits / total) * 100

# ์‚ฌ์šฉ ์˜ˆ์ œ
r = redis.Redis(decode_responses=True)
monitor = CacheMonitor(r)

# ์บ์‹œ ์‚ฌ์šฉ
for i in range(100):
    key = f"product:{i % 10}"  # 10๊ฐœ ์ƒํ’ˆ์„ ๋ฐ˜๋ณต ์กฐํšŒ
    
    data = monitor.get_with_stats(key)
    
    if data is None:
        # ์บ์‹œ ๋ฏธ์Šค - DB ์กฐํšŒ ํ›„ ์ €์žฅ
        data = f"Product {i % 10}"
        r.setex(key, 60, data)

# ํ†ต๊ณ„ ์ถœ๋ ฅ
monitor.print_stats()

# Redis ์„œ๋ฒ„ ์ •๋ณด
info = monitor.get_redis_info()
print(f"\n๐Ÿ–ฅ๏ธ Redis ์„œ๋ฒ„ ์ •๋ณด:")
for key, value in info.items():
    print(f"  {key}: {value}")

print(f"\nโœ… Redis ํžˆํŠธ์œจ: {monitor.calculate_hit_rate_from_redis():.2f}%")
### ๐Ÿ“‰ ์„ฑ๋Šฅ ์ตœ์ ํ™” ํŒ
๐Ÿš€ Redis ์„ฑ๋Šฅ ์ตœ์ ํ™” ์ฒดํฌ๋ฆฌ์ŠคํŠธ 1. ์—ฐ๊ฒฐ ๊ด€๋ฆฌ
โ€ข ์—ฐ๊ฒฐ ํ’€ ์‚ฌ์šฉ (๋งค๋ฒˆ ์ƒˆ ์—ฐ๊ฒฐ ์ƒ์„ฑ ๊ธˆ์ง€)
โ€ข ์ ์ ˆํ•œ ํƒ€์ž„์•„์›ƒ ์„ค์ •
โ€ข Keep-alive ํ™œ์„ฑํ™”

2. ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ ์„ ํƒ
โ€ข ์ž‘์€ ๋ฐ์ดํ„ฐ: String
โ€ข ๋ฆฌ์ŠคํŠธ: List (์ตœ๊ทผ ํ•ญ๋ชฉ, ํ)
โ€ข ์œ ๋‹ˆํฌ ์ง‘ํ•ฉ: Set (ํƒœ๊ทธ, ํŒ”๋กœ์›Œ)
โ€ข ์ˆœ์œ„: Sorted Set (๋žญํ‚น, ๋ฆฌ๋”๋ณด๋“œ)
โ€ข ๊ฐ์ฒด: Hash (์‚ฌ์šฉ์ž ํ”„๋กœํ•„)

3. ๋ฉ”๋ชจ๋ฆฌ ์ตœ์ ํ™”
โ€ข ์ ์ ˆํ•œ TTL ์„ค์ • (์˜์›ํžˆ ์ €์žฅ ๊ธˆ์ง€)
โ€ข ํฐ ๊ฐ์ฒด๋Š” ์••์ถ•ํ•ด์„œ ์ €์žฅ
โ€ข maxmemory-policy ์„ค์ • (LRU ์ถ”์ฒœ)
โ€ข ์ •๊ธฐ์ ์ธ ๋ฉ”๋ชจ๋ฆฌ ๋ชจ๋‹ˆํ„ฐ๋ง

4. ๋„คํŠธ์›Œํฌ ์ตœ์ ํ™”
โ€ข Pipeline ์‚ฌ์šฉ (์—ฌ๋Ÿฌ ๋ช…๋ น ํ•œ ๋ฒˆ์—)
โ€ข Lua ์Šคํฌ๋ฆฝํŠธ๋กœ ์›์ž์  ์—ฐ์‚ฐ
โ€ข ํฐ ๋ฐ์ดํ„ฐ๋Š” ๋ถ„ํ•  ์ €์žฅ

5. ๋ณด์•ˆ
โ€ข ๋น„๋ฐ€๋ฒˆํ˜ธ ์„ค์ • (requirepass)
โ€ข ์œ„ํ—˜ํ•œ ๋ช…๋ น์–ด ๋น„ํ™œ์„ฑํ™” (FLUSHALL, KEYS ๋“ฑ)
โ€ข ๋ฐฉํ™”๋ฒฝ ์„ค์ •
โ€ข SSL/TLS ์‚ฌ์šฉ (Redis 6.0+)
### ๐Ÿ”ง Pipeline ์‚ฌ์šฉ ์˜ˆ์ œ
# Python - Pipeline์œผ๋กœ ์„ฑ๋Šฅ ํ–ฅ์ƒ

import redis
import time

r = redis.Redis()

# ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ• (๋А๋ฆผ)
def save_without_pipeline():
    start = time.time()
    
    for i in range(1000):
        r.set(f"key:{i}", f"value:{i}")
    
    elapsed = time.time() - start
    print(f"Pipeline ์—†์ด: {elapsed:.2f}์ดˆ")

# Pipeline ์‚ฌ์šฉ (๋น ๋ฆ„!)
def save_with_pipeline():
    start = time.time()
    
    pipe = r.pipeline()
    
    for i in range(1000):
        pipe.set(f"key:{i}", f"value:{i}")
    
    pipe.execute()  # ํ•œ ๋ฒˆ์— ์‹คํ–‰!
    
    elapsed = time.time() - start
    print(f"Pipeline ์‚ฌ์šฉ: {elapsed:.2f}์ดˆ")

save_without_pipeline()  # ์•ฝ 1.5์ดˆ
save_with_pipeline()     # ์•ฝ 0.05์ดˆ (30๋ฐฐ ๋น ๋ฆ„!)
๐Ÿ’ก Pipeline ์‚ฌ์šฉ ์‹œ ์ฃผ์˜์‚ฌํ•ญ โ€ข ๋„ˆ๋ฌด ๋งŽ์€ ๋ช…๋ น์„ ํ•œ ๋ฒˆ์— ๋ณด๋‚ด๋ฉด ๋ฉ”๋ชจ๋ฆฌ ๋ถ€์กฑ ๊ฐ€๋Šฅ
โ€ข 1000~5000๊ฐœ ์ •๋„์”ฉ ๋‚˜๋ˆ ์„œ ์‹คํ–‰ ์ถ”์ฒœ
โ€ข ํŠธ๋žœ์žญ์…˜์ด ํ•„์š”ํ•˜๋ฉด MULTI/EXEC ์‚ฌ์šฉ
โ€ข ์—๋Ÿฌ ์ฒ˜๋ฆฌ ๊ผญ ํ•ด์•ผ ํ•ด!
## ๐ŸŽ“ ์‹ค์ „ ํ”„๋กœ์ ํŠธ: ์‡ผํ•‘๋ชฐ ์บ์‹ฑ ์‹œ์Šคํ…œ ๊ตฌ์ถ• ์ด์ œ ๋ฐฐ์šด ๊ฑธ ๋‹ค ํ•ฉ์ณ์„œ ์‹ค์ œ ์‡ผํ•‘๋ชฐ ํ”„๋กœ์ ํŠธ๋ฅผ ๋งŒ๋“ค์–ด๋ณด์ž! ์žฌ๋Šฅ๋„ท ๊ฐ™์€ ํ”Œ๋žซํผ์—์„œ๋„ ์ด๋Ÿฐ ๊ธฐ์ˆ ์ด ๋งŽ์ด ์“ฐ์—ฌ. ๐Ÿ˜Š ### ๐Ÿ—๏ธ ์‹œ์Šคํ…œ ์•„ํ‚คํ…์ฒ˜
์‚ฌ์šฉ์ž ์š”์ฒญ
    โ†“
[Load Balancer]
    โ†“
[Web Server (Node.js/Python/Java)]
    โ†“
[Redis Cache Layer]
    โ†“
[Database (MySQL/PostgreSQL)]
### ๐Ÿ’ป ์ „์ฒด ๊ตฌํ˜„ ์˜ˆ์ œ (Node.js + Express)
// app.js - ์‡ผํ•‘๋ชฐ API ์„œ๋ฒ„

const express = require('express');
const Redis = require('ioredis');
const mysql = require('mysql2/promise');

const app = express();
app.use(express.json());

// Redis ์—ฐ๊ฒฐ (ํด๋Ÿฌ์Šคํ„ฐ ๋ชจ๋“œ)
const redis = new Redis.Cluster([
  { host: 'redis-node1', port: 6379 },
  { host: 'redis-node2', port: 6379 },
  { host: 'redis-node3', port: 6379 }
]);

// MySQL ์—ฐ๊ฒฐ ํ’€
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'shop',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// ===== 1. ์ƒํ’ˆ ์กฐํšŒ (Cache-Aside ํŒจํ„ด) =====
app.get('/api/products/:id', async (req, res) => {
  const productId = req.params.id;
  const cacheKey = `product:${productId}`;
  
  try {
    // ์บ์‹œ ํ™•์ธ
    const cached = await redis.get(cacheKey);
    
    if (cached) {
      console.log('โœ… ์บ์‹œ ํžˆํŠธ');
      return res.json({
        source: 'cache',
        data: JSON.parse(cached)
      });
    }
    
    // ์บ์‹œ ๋ฏธ์Šค - DB ์กฐํšŒ
    console.log('๐Ÿ“€ ์บ์‹œ ๋ฏธ์Šค - DB ์กฐํšŒ');
    const [rows] = await pool.query(
      'SELECT * FROM products WHERE id = ?',
      [productId]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({ error: '์ƒํ’ˆ ์—†์Œ' });
    }
    
    const product = rows[0];
    
    // ์บ์‹œ์— ์ €์žฅ (1์‹œ๊ฐ„)
    await redis.setex(cacheKey, 3600, JSON.stringify(product));
    
    res.json({
      source: 'database',
      data: product
    });
    
  } catch (error) {
    console.error('์—๋Ÿฌ:', error);
    res.status(500).json({ error: '์„œ๋ฒ„ ์—๋Ÿฌ' });
  }
});

// ===== 2. ์ธ๊ธฐ ์ƒํ’ˆ ๋ชฉ๋ก (Refresh-Ahead ํŒจํ„ด) =====
app.get('/api/products/popular', async (req, res) => {
  const cacheKey = 'products:popular';
  
  try {
    const cached = await redis.get(cacheKey);
    
    if (cached) {
      // TTL ํ™•์ธ
      const ttl = await redis.ttl(cacheKey);
      
      // 5๋ถ„ ์ดํ•˜ ๋‚จ์œผ๋ฉด ๋ฐฑ๊ทธ๋ผ์šด๋“œ ๊ฐฑ์‹ 
      if (ttl < 300) {
        refreshPopularProducts();  // ๋น„๋™๊ธฐ ๊ฐฑ์‹ 
      }
      
      return res.json({
        source: 'cache',
        data: JSON.parse(cached)
      });
    }
    
    // ์บ์‹œ ๋ฏธ์Šค
    const products = await loadPopularProducts();
    await redis.setex(cacheKey, 1800, JSON.stringify(products));
    
    res.json({
      source: 'database',
      data: products
    });
    
  } catch (error) {
    res.status(500).json({ error: '์„œ๋ฒ„ ์—๋Ÿฌ' });
  }
});

async function loadPopularProducts() {
  const [rows] = await pool.query(`
    SELECT p.*, COUNT(o.id) as sales
    FROM products p
    LEFT JOIN orders o ON p.id = o.product_id
    WHERE o.created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY p.id
    ORDER BY sales DESC
    LIMIT 20
  `);
  return rows;
}

async function refreshPopularProducts() {
  console.log('๐Ÿ”„ ์ธ๊ธฐ ์ƒํ’ˆ ๊ฐฑ์‹  ์ค‘...');
  const products = await loadPopularProducts();
  await redis.setex('products:popular', 1800, JSON.stringify(products));
  console.log('โœ… ์ธ๊ธฐ ์ƒํ’ˆ ๊ฐฑ์‹  ์™„๋ฃŒ');
}

// ===== 3. ์žฅ๋ฐ”๊ตฌ๋‹ˆ (Redis Set ํ™œ์šฉ) =====
app.post('/api/cart/:userId/add', async (req, res) => {
  const userId = req.params.userId;
  const { productId, quantity } = req.body;
  
  const cartKey = `cart:${userId}`;
  
  try {
    // ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ƒํ’ˆ ์ถ”๊ฐ€ (Hash ์‚ฌ์šฉ)
    await redis.hset(cartKey, productId, quantity);
    
    // 7์ผ ํ›„ ์ž๋™ ์‚ญ์ œ
    await redis.expire(cartKey, 7 * 24 * 3600);
    
    // ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ „์ฒด ์กฐํšŒ
    const cart = await redis.hgetall(cartKey);
    
    res.json({
      success: true,
      cart: cart
    });
    
  } catch (error) {
    res.status(500).json({ error: '์„œ๋ฒ„ ์—๋Ÿฌ' });
  }
});

app.get('/api/cart/:userId', async (req, res) => {
  const userId = req.params.userId;
  const cartKey = `cart:${userId}`;
  
  try {
    const cart = await redis.hgetall(cartKey);
    
    // ์ƒํ’ˆ ์ •๋ณด ์กฐํšŒ (Pipeline ์‚ฌ์šฉ)
    const productIds = Object.keys(cart);
    const pipeline = redis.pipeline();
    
    productIds.forEach(id => {
      pipeline.get(`product:${id}`);
    });
    
    const results = await pipeline.exec();
    
    const cartItems = productIds.map((id, index) => {
      const product = JSON.parse(results[index][1]);
      return {
        ...product,
        quantity: parseInt(cart[id])
      };
    });
    
    res.json({
      items: cartItems,
      total: cartItems.reduce((sum, item) => 
        sum + (item.price * item.quantity), 0
      )
    });
    
  } catch (error) {
    res.status(500).json({ error: '์„œ๋ฒ„ ์—๋Ÿฌ' });
  }
});

// ===== 4. ์‹ค์‹œ๊ฐ„ ์žฌ๊ณ  ๊ด€๋ฆฌ =====
app.post('/api/orders', async (req, res) => {
  const { userId, productId, quantity } = req.body;
  const stockKey = `stock:${productId}`;
  const lockKey = `lock:order:${productId}`;
  
  try {
    // ๋ถ„์‚ฐ ๋ฝ ํš๋“ (10์ดˆ ํƒ€์ž„์•„์›ƒ)
    const lockAcquired = await redis.set(
      lockKey,
      'locked',
      'EX', 10,
      'NX'
    );
    
    if (!lockAcquired) {
      return res.status(409).json({ error: '์ฒ˜๋ฆฌ ์ค‘์ž…๋‹ˆ๋‹ค' });
    }
    
    try {
      // ์žฌ๊ณ  ํ™•์ธ
      let stock = await redis.get(stockKey);
      
      if (!stock) {
        // ์บ์‹œ์— ์—†์œผ๋ฉด DB์—์„œ ๋กœ๋“œ
        const [rows] = await pool.query(
          'SELECT stock FROM products WHERE id = ?',
          [productId]
        );
        stock = rows[0].stock;
        await redis.set(stockKey, stock);
      }
      
      stock = parseInt(stock);
      
      if (stock < quantity) {
        return res.status(400).json({ error: '์žฌ๊ณ  ๋ถ€์กฑ' });
      }
      
      // ์žฌ๊ณ  ๊ฐ์†Œ
      await redis.decrby(stockKey, quantity);
      
      // ์ฃผ๋ฌธ ์ƒ์„ฑ (DB)
      const [result] = await pool.query(
        'INSERT INTO orders (user_id, product_id, quantity) VALUES (?, ?, ?)',
        [userId, productId, quantity]
      );
      
      // DB ์žฌ๊ณ ๋„ ์—…๋ฐ์ดํŠธ
      await pool.query(
        'UPDATE products SET stock = stock - ? WHERE id = ?',
        [quantity, productId]
      );
      
      res.json({
        success: true,
        orderId: result.insertId,
        remainingStock: stock - quantity
      });
      
    } finally {
      // ๋ฝ ํ•ด์ œ
      await redis.del(lockKey);
    }
    
  } catch (error) {
    console.error('์ฃผ๋ฌธ ์—๋Ÿฌ:', error);
    res.status(500).json({ error: '์„œ๋ฒ„ ์—๋Ÿฌ' });
  }
});

// ===== 5. ์‹ค์‹œ๊ฐ„ ์ˆœ์œ„ (Sorted Set) =====
app.post('/api/products/:id/view', async (req, res) => {
  const productId = req.params.id;
  const rankingKey = 'products:ranking:views';
  
  try {
    // ์กฐํšŒ์ˆ˜ ์ฆ๊ฐ€
    await redis.zincrby(rankingKey, 1, productId);
    
    // ํ˜„์žฌ ์ˆœ์œ„ ์กฐํšŒ
    const rank = await redis.zrevrank(rankingKey, productId);
    const score = await redis.zscore(rankingKey, productId);
    
    res.json({
      productId,
      views: parseInt(score),
      rank: rank + 1
    });
    
  } catch (error) {
    res.status(500).json({ error: '์„œ๋ฒ„ ์—๋Ÿฌ' });
  }
});

app.get('/api/products/ranking/top', async (req, res) => {
  const limit = parseInt(req.query.limit) || 10;
  const rankingKey = 'products:ranking:views';
  
  try {
    // Top N ์กฐํšŒ (์ ์ˆ˜ ํฌํ•จ)
    const results = await redis.zrevrange(
      rankingKey,
      0,
      limit - 1,
      'WITHSCORES'
    );
    
    // ์ƒํ’ˆ ์ •๋ณด ์กฐํšŒ
    const rankings = [];
    for (let i = 0; i < results.length; i += 2) {
      const productId = results[i];
      const views = parseInt(results[i + 1]);
      
      const product = await redis.get(`product:${productId}`);
      
      rankings.push({
        rank: (i / 2) + 1,
        product: JSON.parse(product),
        views
      });
    }
    
    res.json({ rankings });
    
  } catch (error) {
    res.status(500).json({ error: '์„œ๋ฒ„ ์—๋Ÿฌ' });
  }
});

// ===== 6. ์„ธ์…˜ ๊ด€๋ฆฌ =====
const session = require('express-session');
const RedisStore = require('connect-redis')(session);

app.use(session({
  store: new RedisStore({ client: redis }),
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: false,  // HTTPS์—์„œ๋Š” true
    httpOnly: true,
    maxAge: 1000 * 60 * 60 * 24  // 1์ผ
  }
}));

app.post('/api/login', async (req, res) => {
  const { username, password } = req.body;
  
  // ๋กœ๊ทธ์ธ ๊ฒ€์ฆ (์‹ค์ œ๋กœ๋Š” bcrypt ์‚ฌ์šฉ)
  const [rows] = await pool.query(
    'SELECT * FROM users WHERE username = ? AND password = ?',
    [username, password]
  );
  
  if (rows.length === 0) {
    return res.status(401).json({ error: '๋กœ๊ทธ์ธ ์‹คํŒจ' });
  }
  
  const user = rows[0];
  
  // ์„ธ์…˜์— ์‚ฌ์šฉ์ž ์ •๋ณด ์ €์žฅ
  req.session.userId = user.id;
  req.session.username = user.username;
  
  res.json({
    success: true,
    user: {
      id: user.id,
      username: user.username
    }
  });
});

// ์ธ์ฆ ๋ฏธ๋“ค์›จ์–ด
function requireAuth(req, res, next) {
  if (!req.session.userId) {
    return res.status(401).json({ error: '๋กœ๊ทธ์ธ ํ•„์š”' });
  }
  next();
}

app.get('/api/profile', requireAuth, async (req, res) => {
  res.json({
    userId: req.session.userId,
    username: req.session.username
  });
});

// ===== 7. ๋ชจ๋‹ˆํ„ฐ๋ง ์—”๋“œํฌ์ธํŠธ =====
app.get('/api/stats/cache', async (req, res) => {
  try {
    const info = await redis.info('stats');
    
    // ์ •๋ณด ํŒŒ์‹ฑ
    const lines = info.split('\r\n');
    const stats = {};
    
    lines.forEach(line => {
      const [key, value] = line.split(':');
      if (key && value) {
        stats[key] = value;
      }
    });
    
    const hits = parseInt(stats.keyspace_hits || 0);
    const misses = parseInt(stats.keyspace_misses || 0);
    const total = hits + misses;
    
    res.json({
      hits,
      misses,
      total,
      hitRate: total > 0 ? ((hits / total) * 100).toFixed(2) + '%' : '0%',
      evictedKeys: stats.evicted_keys || 0,
      connectedClients: stats.connected_clients || 0
    });
    
  } catch (error) {
    res.status(500).json({ error: '์„œ๋ฒ„ ์—๋Ÿฌ' });
  }
});

// ์„œ๋ฒ„ ์‹œ์ž‘
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`๐Ÿš€ ์„œ๋ฒ„ ์‹œ์ž‘: http://localhost:${PORT}`);
  console.log('๐Ÿ“Š ์บ์‹œ ํ†ต๊ณ„: http://localhost:${PORT}/api/stats/cache');
});

// Graceful Shutdown
process.on('SIGTERM', async () => {
  console.log('๐Ÿ‘‹ ์„œ๋ฒ„ ์ข…๋ฃŒ ์ค‘...');
  await redis.quit();
  await pool.end();
  process.exit(0);
});
๐ŸŽฏ ์ด ํ”„๋กœ์ ํŠธ์—์„œ ์‚ฌ์šฉํ•œ ์บ์‹ฑ ๊ธฐ๋ฒ• ์ •๋ฆฌ 1. Cache-Aside - ์ƒํ’ˆ ์กฐํšŒ
2. Refresh-Ahead - ์ธ๊ธฐ ์ƒํ’ˆ ๋ชฉ๋ก
3. Redis Hash - ์žฅ๋ฐ”๊ตฌ๋‹ˆ
4. ๋ถ„์‚ฐ ๋ฝ - ์žฌ๊ณ  ๊ด€๋ฆฌ
5. Sorted Set - ์‹ค์‹œ๊ฐ„ ์ˆœ์œ„
6. ์„ธ์…˜ ์ €์žฅ์†Œ - ๋กœ๊ทธ์ธ ์ƒํƒœ
7. Pipeline - ๋Œ€๋Ÿ‰ ์กฐํšŒ ์ตœ์ ํ™”
## ๐ŸŒŸ ๋งˆ๋ฌด๋ฆฌํ•˜๋ฉฐ ์™€! ์—ฌ๊ธฐ๊นŒ์ง€ ์ฝ์—ˆ๋‹ค๋ฉด ์ •๋ง ๋Œ€๋‹จํ•ด! ๐Ÿ‘ ์บ์‹ฑ์€ ์ฒ˜์Œ์—” ์–ด๋ ค์›Œ ๋ณด์ด์ง€๋งŒ, ๋ง‰์ƒ ์จ๋ณด๋ฉด ์ •๋ง ๊ฐ•๋ ฅํ•œ ๋„๊ตฌ์•ผ. ์‘์šฉํ”„๋กœ๊ทธ๋ž˜๋ฐ์—์„œ ์„ฑ๋Šฅ ์ตœ์ ํ™”๋Š” ํ•„์ˆ˜์ธ๋ฐ, ์บ์‹ฑ์ด ๊ทธ ํ•ต์‹ฌ์ด๊ฑฐ๋“ !
๐ŸŽ“ ํ•ต์‹ฌ ์š”์•ฝ 1. ์บ์‹ฑ์˜ ๊ธฐ๋ณธ
โ€ข ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋น ๋ฅธ ์ €์žฅ์†Œ์— ๋ณด๊ด€
โ€ข ์‘๋‹ต ์†๋„ 10~100๋ฐฐ ํ–ฅ์ƒ ๊ฐ€๋Šฅ
โ€ข DB ๋ถ€ํ•˜ ๋Œ€ํญ ๊ฐ์†Œ

2. Redis vs Memcached
โ€ข Redis: ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ, ์˜์†์„ฑ, ๋ณต์žกํ•œ ์ž๋ฃŒ๊ตฌ์กฐ
โ€ข Memcached: ๋‹จ์ˆœํ•จ, ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ, ๋ฉ€ํ‹ฐ์Šค๋ ˆ๋“œ
โ€ข ๋Œ€๋ถ€๋ถ„์˜ ๊ฒฝ์šฐ Redis ์ถ”์ฒœ

3. ์บ์‹ฑ ์ „๋žต
โ€ข Cache-Aside: ๊ฐ€์žฅ ์ผ๋ฐ˜์ 
โ€ข Write-Through: ์ผ๊ด€์„ฑ ์ค‘์š”ํ•  ๋•Œ
โ€ข Write-Behind: ์„ฑ๋Šฅ ์ตœ์šฐ์„ ์ผ ๋•Œ
โ€ข Read-Through: ์บ์‹œ๊ฐ€ DB ๊ด€๋ฆฌ
โ€ข Refresh-Ahead: ํ•ซ ๋ฐ์ดํ„ฐ ๋ฏธ๋ฆฌ ๊ฐฑ์‹ 

4. ์ฃผ์˜์‚ฌํ•ญ
โ€ข Cache Stampede ๋ฐฉ์ง€ (๋ถ„์‚ฐ ๋ฝ)
โ€ข Cache Invalidation ์ „๋žต ์ˆ˜๋ฆฝ
โ€ข Cache Penetration ๋Œ€์‘ (Null ์บ์‹ฑ, Bloom Filter)
โ€ข Cache Avalanche ๋ฐฉ์ง€ (TTL ๋ถ„์‚ฐ)
โ€ข ๋ณด์•ˆ (๋ฏผ๊ฐ ์ •๋ณด ์•”ํ˜ธํ™”)

5. ๋ชจ๋‹ˆํ„ฐ๋ง
โ€ข Hit Rate 80% ์ด์ƒ ๋ชฉํ‘œ
โ€ข ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋ฅ  70~80% ์œ ์ง€
โ€ข Latency 1ms ์ดํ•˜
โ€ข ์ •๊ธฐ์ ์ธ ์„ฑ๋Šฅ ๋ถ„์„
### ๐Ÿš€ ๋‹ค์Œ ๋‹จ๊ณ„ ์บ์‹ฑ์„ ๋งˆ์Šคํ„ฐํ–ˆ๋‹ค๋ฉด ์ด์ œ ์ด๋Ÿฐ ๊ฒƒ๋“ค๋„ ๊ณต๋ถ€ํ•ด๋ณด์ž: 1. **Redis Cluster** - ๋Œ€์šฉ๋Ÿ‰ ๋ฐ์ดํ„ฐ ๋ถ„์‚ฐ ์ฒ˜๋ฆฌ ๐ŸŒ 2. **Redis Sentinel** - ๊ณ ๊ฐ€์šฉ์„ฑ ๊ตฌ์„ฑ ๐Ÿ›ก๏ธ 3. CDN ์บ์‹ฑ - ์ •์  ํŒŒ์ผ ์ „์†ก ์ตœ์ ํ™” ๐Ÿ“ฆ 4. ๋ธŒ๋ผ์šฐ์ € ์บ์‹ฑ - ํด๋ผ์ด์–ธํŠธ ์‚ฌ์ด๋“œ ์บ์‹ฑ ๐Ÿ’ป 5. **Varnish** - HTTP ์บ์‹ฑ ์„œ๋ฒ„ โšก 6. **ElastiCache** - AWS ๊ด€๋ฆฌํ˜• ์บ์‹œ โ˜๏ธ ### ๐Ÿ’ฌ ์žฌ๋Šฅ๋„ท์—์„œ ๋” ๋ฐฐ์šฐ๊ธฐ ์žฌ๋Šฅ๋„ท(https://www.jaenung.net)์—๋Š” ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๊ณ ์ˆ˜๋“ค์ด ๋งŽ์•„! ์บ์‹ฑ ๊ด€๋ จํ•ด์„œ ๊ถ๊ธˆํ•œ ๊ฒŒ ์žˆ๊ฑฐ๋‚˜, ์‹ค์ „ ํ”„๋กœ์ ํŠธ์— ์ ์šฉํ•˜๋‹ค๊ฐ€ ๋ง‰ํžˆ๋ฉด ์žฌ๋Šฅ๋„ท์˜ '์ง€์‹์ธ์˜ ์ˆฒ'์—์„œ ์งˆ๋ฌธํ•˜๊ฑฐ๋‚˜, ์ „๋ฌธ๊ฐ€์—๊ฒŒ 1:1 ์ปจ์„คํŒ…์„ ๋ฐ›์•„๋ณผ ์ˆ˜๋„ ์žˆ์–ด. ๋‚˜๋„ ์ฒ˜์Œ์—” ํ˜ผ์ž ์‚ฝ์งˆํ•˜๋‹ค๊ฐ€ ๊ณ ์ˆ˜๋“คํ•œํ…Œ ๋ฐฐ์›Œ์„œ ์‹ค๋ ฅ์ด ์‘ฅ์‘ฅ ๋Š˜์—ˆ๊ฑฐ๋“ ! ๐Ÿ˜„ ์บ์‹ฑ์€ ํ•œ ๋ฒˆ ์ œ๋Œ€๋กœ ๊ตฌ์ถ•ํ•ด๋‘๋ฉด ์ •๋ง ๋“ ๋“ ํ•œ ์นœ๊ตฌ๊ฐ€ ๋ผ. ์‚ฌ์šฉ์ž๋Š” ๋น ๋ฅธ ์†๋„์— ๋งŒ์กฑํ•˜๊ณ , ์„œ๋ฒ„๋Š” ์—ฌ์œ ๋กญ๊ณ , ๊ฐœ๋ฐœ์ž๋Š” ๋ฟŒ๋“ฏํ•˜๊ณ ! ์ผ์„์‚ผ์กฐ์ง€! ๐ŸŽ‰ ์ž, ์ด์ œ ๋‹น์‹ ์˜ ํ”„๋กœ์ ํŠธ์— ์บ์‹ฑ์„ ์ ์šฉํ•ด๋ณผ ์‹œ๊ฐ„์ด์•ผ! ํ™”์ดํŒ…! ๐Ÿ’ชโœจ
๐ŸŽŠ
์ถ•ํ•˜ํ•ฉ๋‹ˆ๋‹ค!
์บ์‹ฑ ๋งˆ์Šคํ„ฐ์˜ ๊ธธ์— ํ•œ ๊ฑธ์Œ ๋” ๋‹ค๊ฐ€๊ฐ”์–ด์š”!
์ด์ œ ๋‹น์‹ ์˜ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ๋‚ ๊ฐœ ๋‹ฌ์•„์ฃผ์„ธ์š”! ๐Ÿš€
๋Œ“๊ธ€ ์ž‘์„ฑ

์ด ๊ธ€์— ๋Œ€ํ•œ ์—ฌ๋Ÿฌ๋ถ„์˜ ์ƒ๊ฐ์„ ๋“ค๋ ค์ฃผ์„ธ์š”

๋Œ“๊ธ€ 0
๋Œ“๊ธ€์„ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ค‘์ž…๋‹ˆ๋‹ค.

์•„์ง ๋Œ“๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค.