Ver3.0 ๐ ์์ฉํ๋ก๊ทธ๋๋ฐ์์ ์บ์ฑ ๊ธฐ๋ฒ ์ ์ฉํ๊ธฐ

๐ ์์ฉํ๋ก๊ทธ๋๋ฐ์์ ์บ์ฑ ๊ธฐ๋ฒ ์ ์ฉํ๊ธฐ
์น๊ตฌ์ฒ๋ผ ์ฝ๊ฒ ์๋ ค์ฃผ๋ ์บ์ฑ์ ๋ชจ๋ ๊ฒ
| ํน์ง | Redis ๐ด | Memcached ๐ข |
|---|---|---|
| ๋ฐ์ดํฐ ํ์ | String, List, Set, Hash, Sorted Set ๋ฑ ๋ค์ | String๋ง ์ง์ |
| ์์์ฑ | ๋์คํฌ ์ ์ฅ ๊ฐ๋ฅ (RDB, AOF) | ๋ฉ๋ชจ๋ฆฌ๋ง ์ฌ์ฉ (์ฌ์์ ์ ๋ฐ์ดํฐ ์์ค) |
| ๋ณต์ | Master-Slave ๋ณต์ ์ง์ | ๋ณต์ ๊ธฐ๋ฅ ์์ |
| ํธ๋์ญ์ | ์ง์ | ๋ฏธ์ง์ |
| Pub/Sub | ์ง์ | ๋ฏธ์ง์ |
| ๋ฉ๋ชจ๋ฆฌ ํจ์จ | ๋ณดํต | ์ฐ์ |
| ์๋ | ๋งค์ฐ ๋น ๋ฆ | ์ฝ๊ฐ ๋ ๋น ๋ฆ |
| ๋ฉํฐ์ค๋ ๋ | ์ฑ๊ธ์ค๋ ๋ (6.0๋ถํฐ ์ผ๋ถ ๋ฉํฐ์ค๋ ๋) | ๋ฉํฐ์ค๋ ๋ |
โข ๋ฐ์ดํฐ ์์์ฑ์ด ์ค์ํ ๋ ๐พ
โข ์ค์๊ฐ ์์ํ, ์ฑํ ๊ฐ์ ๋ณต์กํ ๊ธฐ๋ฅ์ด ํ์ํ ๋ ๐ฎ
โข ๋ถ์ฐ ๋ฝ(Lock)์ด๋ ์ธ์ ๊ด๋ฆฌ๊ฐ ํ์ํ ๋ ๐
โข Pub/Sub ๋ฉ์์ง ํจํด์ ์ฌ์ฉํ ๋ ๐ข
โข ๋ฉ๋ชจ๋ฆฌ ํจ์จ์ด ์ต์ฐ์ ์ผ ๋ ๐ช
โข ๋ฉํฐ์ค๋ ๋ ํ๊ฒฝ์์ ์ต๋ ์ฑ๋ฅ์ด ํ์ํ ๋ โก
โข ๋ฐ์ดํฐ ์ ์ค์ด ํฌ๊ฒ ๋ฌธ์ ๋์ง ์์ ๋ ๐คท
โข ์ค์ ๊ณผ ์ด์์ด ๋จ์ํด์ผ ํ ๋ ๐ฏ
# 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
GET key - ๋ฐ์ดํฐ ์กฐํ
DEL key - ๋ฐ์ดํฐ ์ญ์
EXISTS key - ํค ์กด์ฌ ํ์ธ
EXPIRE key seconds - ๋ง๋ฃ ์๊ฐ ์ค์
TTL key - ๋จ์ ๋ง๋ฃ ์๊ฐ ํ์ธ
KEYS pattern - ํจํด์ผ๋ก ํค ๊ฒ์ (์ด์์์ ์ฃผ์!)
FLUSHALL - ๋ชจ๋ ๋ฐ์ดํฐ ์ญ์ (์กฐ์ฌ!)
# ๋ฌธ์์ด ์ ์ฅ
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 ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ค์น
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)}")
โข JSON ๋ฐ์ดํฐ๋ json.dumps()๋ก ์ง๋ ฌํํด์ ์ ์ฅํ๊ณ , json.loads()๋ก ๋ณต์ํด
โข ์ฐ๊ฒฐ ํ์ ์ฌ์ฉํ๋ฉด ์ฑ๋ฅ์ด ๋ ์ข์์ ธ: redis.ConnectionPool()
โข Pipeline์ ์ฐ๋ฉด ์ฌ๋ฌ ๋ช ๋ น์ ํ ๋ฒ์ ๋ณด๋ผ ์ ์์ด (๋คํธ์ํฌ ์๋ณต ๊ฐ์)
// 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);
}
}
โข @CachePut - ์บ์ ์ ๋ฐ์ดํธ (์์ )
โข @CacheEvict - ์บ์ ์ญ์
โข RedisTemplate - ์ง์ Redis ์กฐ์
โข ์ง๋ ฌํ ์ค์ ์ด ์ค์ํด! JSON ์ง๋ ฌํ ์ถ์ฒ
# 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');
});
โข async/await๋ฅผ ๊ผญ ์ฌ์ฉํด (์ฝ๋ฐฑ ์ง์ฅ ๋ฐฉ์ง)
โข ์๋ฌ ํธ๋ค๋ง ํ์! Redis ์๋ฒ๊ฐ ๋ค์ด๋๋ฉด ์ฑ์ด ๋ฉ์ถ ์ ์์ด
โข Pub/Sub ์ฌ์ฉ ์ ๊ตฌ๋ ์์ ๋ฐํ์๋ ๋ณ๋ ์ฐ๊ฒฐ ํ์
# 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();
}
}
}
โข ๋จ์ ๋ฌธ์์ด ์บ์ฑ๋ง ํ์ (HTML ์กฐ๊ฐ, API ์๋ต ๋ฑ)
โข ๋ฉ๋ชจ๋ฆฌ๊ฐ ์ ํ์ ์ด๊ณ ํจ์จ์ด ์ค์
โข ๋ฉํฐ์ฝ์ด CPU๋ฅผ ์ต๋ํ ํ์ฉํ๊ณ ์ถ์ ๋
Redis๊ฐ ๋ ๋์ ๊ฒฝ์ฐ:
โข ๋ฆฌ์คํธ, ์ , ํด์ ๊ฐ์ ๋ณต์กํ ์๋ฃ๊ตฌ์กฐ ํ์
โข ๋ฐ์ดํฐ ์์์ฑ์ด ํ์ (์๋ฒ ์ฌ์์ ํ์๋ ์ ์ง)
โข ์ค์๊ฐ ์์ํ, ์ฑํ , ์ธ์ ๊ด๋ฆฌ ๋ฑ
โข ๋ถ์ฐ ๋ฝ, Pub/Sub ๊ฐ์ ๊ณ ๊ธ ๊ธฐ๋ฅ ํ์
// 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}")
โข ์บ์ ์ฅ์ ์์๋ ์ ํ๋ฆฌ์ผ์ด์ ๋์ (DB๋ก ํด๋ฐฑ)
โข ํ์ํ ๋ฐ์ดํฐ๋ง ์บ์ฑ (๋ฉ๋ชจ๋ฆฌ ํจ์จ์ )
โ Cache-Aside ๋จ์
โข ์ฒซ ์์ฒญ์ ํญ์ ๋๋ฆผ (์บ์ ๋ฏธ์ค)
โข ์บ์์ 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 ๋จ์
โข ์ฐ๊ธฐ ์ฑ๋ฅ ์ ํ (๋ ๊ณณ์ ๋ชจ๋ ์จ์ผ ํจ)
โข ์ฌ์ฉํ์ง ์๋ ๋ฐ์ดํฐ๋ ์บ์ฑ (๋ฉ๋ชจ๋ฆฌ ๋ญ๋น)
โข ๊ตฌํ ๋ณต์ก๋ ์ฆ๊ฐ
// 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)
โข ๋ณต์กํ ์๋ฌ ์ฒ๋ฆฌ ํ์
โข ์ฌ์๋ ๋ก์ง ํ์
โข ๊ธ์ต ๊ฑฐ๋ ๊ฐ์ ์ค์ ๋ฐ์ดํฐ์ ๋ถ์ ํฉ
โข ๋ก๊ทธ, ํต๊ณ ๊ฐ์ ๋ฐ์ดํฐ์ ์ ํฉ
// 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)
โข ์์ธก ๊ฐ๋ฅํ ํธ๋ํฝ ํจํด์ ํจ๊ณผ์
โข ๊ฐฑ์ ๋น์ฉ์ด ๋์ ๋ฐ์ดํฐ์ ์ ์ฉ
โข ๋ฐฑ๊ทธ๋ผ์ด๋ ์์ ์ด๋ฏ๋ก ์ฌ์ฉ์ ๊ฒฝํ ํฅ์
โข ๋จ, ๋ชจ๋ ๋ฐ์ดํฐ์ ์ ์ฉํ๋ฉด ๋ฆฌ์์ค ๋ญ๋น!
// ๋ฌธ์ ์ํฉ
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:*") # ๋ชจ๋ ์ํ ๋ชฉ๋ก ์บ์ ์ญ์
// ๋ฌธ์ ์ํฉ
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);
}
| ์งํ | ์ค๋ช | ๋ชฉํ |
|---|---|---|
| Hit Rate | ์บ์์์ ์ฐพ์ ๋น์จ | 80% ์ด์ |
| Miss Rate | ์บ์์ ์์ด์ DB ์กฐํํ ๋น์จ | 20% ์ดํ |
| Eviction Rate | ๋ฉ๋ชจ๋ฆฌ ๋ถ์กฑ์ผ๋ก ์ญ์ ๋ ๋น์จ | ๋ฎ์์๋ก ์ข์ |
| Latency | ์บ์ ์๋ต ์๊ฐ | 1ms ์ดํ |
| Memory Usage | ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ๋ฅ | 70~80% |
| Connection Count | ๋์ ์ฐ๊ฒฐ ์ | ์ ์ ํ ๊ด๋ฆฌ |
# 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}%")
### ๐ ์ฑ๋ฅ ์ต์ ํ ํ
โข ์ฐ๊ฒฐ ํ ์ฌ์ฉ (๋งค๋ฒ ์ ์ฐ๊ฒฐ ์์ฑ ๊ธ์ง)
โข ์ ์ ํ ํ์์์ ์ค์
โข 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+)
# 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๋ฐฐ ๋น ๋ฆ!)
โข 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);
});
2. Refresh-Ahead - ์ธ๊ธฐ ์ํ ๋ชฉ๋ก
3. Redis Hash - ์ฅ๋ฐ๊ตฌ๋
4. ๋ถ์ฐ ๋ฝ - ์ฌ๊ณ ๊ด๋ฆฌ
5. Sorted Set - ์ค์๊ฐ ์์
6. ์ธ์ ์ ์ฅ์ - ๋ก๊ทธ์ธ ์ํ
7. Pipeline - ๋๋ ์กฐํ ์ต์ ํ
โข ์์ฃผ ์ฌ์ฉํ๋ ๋ฐ์ดํฐ๋ฅผ ๋น ๋ฅธ ์ ์ฅ์์ ๋ณด๊ด
โข ์๋ต ์๋ 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 ์ดํ
โข ์ ๊ธฐ์ ์ธ ์ฑ๋ฅ ๋ถ์
์ด์ ๋น์ ์ ์ ํ๋ฆฌ์ผ์ด์ ์ ๋ ๊ฐ ๋ฌ์์ฃผ์ธ์! ๐
๊ด๋ จ ํค์๋
๋๊ธ ์์ฑ
์ด ๊ธ์ ๋ํ ์ฌ๋ฌ๋ถ์ ์๊ฐ์ ๋ค๋ ค์ฃผ์ธ์
๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค
๋๊ธ์ ์์ฑํ๋ ค๋ฉด ๋จผ์ ๋ก๊ทธ์ธํด์ฃผ์ธ์.
๋๊ธ 0
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.