Redis kullanarak web uygulamanızın performansını dramatik şekilde artırın
Daha Hızlı
Sayfa Yükleme
Veritabanı
Yük Azalması
Kullanıcı Deneyimi
İyileşmesi
Redis (Remote Dictionary Server), in-memory veri yapısı deposu olarak çalışan açık kaynak kodlu bir NoSQL veritabanıdır. Web uygulamalarında cache, session store ve message broker olarak kullanılır.
// package.json
npm install redis
// Redis bağlantısı
const redis = require('redis');
const client = redis.createClient({
host: 'localhost',
port: 6379
});
client.connect();
client.on('error', (err) => {
console.log('Redis Client Error', err);
});
// Basit cache örneği
const cacheData = async (key, data, expiration = 3600) => {
await client.setEx(key, expiration, JSON.stringify(data));
};
const getCachedData = async (key) => {
const data = await client.get(key);
return data ? JSON.parse(data) : null;
};
// cache middleware
const cacheMiddleware = (duration = 300) => {
return async (req, res, next) => {
const key = `cache:${req.originalUrl}`;
try {
const cachedData = await getCachedData(key);
if (cachedData) {
return res.json(cachedData);
}
// Original response'u yakala
const originalSend = res.send;
res.send = function(data) {
// Cache'e kaydet
cacheData(key, JSON.parse(data), duration);
originalSend.call(this, data);
};
next();
} catch (error) {
next();
}
};
};
// Kullanım
app.get('/api/products', cacheMiddleware(600), async (req, res) => {
const products = await Product.findAll();
res.json(products);
});
// config/cache.php
'default' => 'redis',
'stores' => [
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'prefix' => env('CACHE_PREFIX', 'laravel_cache'),
],
],
// Controller'da kullanım
use Illuminate\Support\Facades\Cache;
class ProductController extends Controller
{
public function index()
{
$products = Cache::remember('products', 600, function () {
return Product::with('category')->get();
});
return response()->json($products);
}
public function store(Request $request)
{
$product = Product::create($request->all());
// Cache'i temizle
Cache::forget('products');
return response()->json($product);
}
}
const getUserById = async (userId) => {
// Önce cache'e bak
let user = await getCachedData(`user:${userId}`);
if (!user) {
// Cache miss - veritabanından al
user = await User.findById(userId);
if (user) {
// Cache'e kaydet
await cacheData(`user:${userId}`, user, 1800);
}
}
return user;
};
const updateUser = async (userId, userData) => {
// Veritabanını güncelle
const user = await User.findByIdAndUpdate(userId, userData, { new: true });
// Cache'i de güncelle
await cacheData(`user:${userId}`, user, 1800);
return user;
};
// String
await client.set('username', 'osman');
const username = await client.get('username');
// Hash
await client.hSet('user:1', {
name: 'Osman',
email: 'osman@example.com',
age: '25'
});
// List
await client.lPush('recent_users', 'user:1');
await client.lPush('recent_users', 'user:2');
// Set
await client.sAdd('online_users', 'user:1');
await client.sAdd('online_users', 'user:2');
// Sorted Set
await client.zAdd('leaderboard', [
{ score: 100, value: 'user:1' },
{ score: 95, value: 'user:2' }
]);
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore({ client: client }),
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // HTTPS için true
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 // 24 saat
}
}));
// TTL (Time To Live) ile otomatik silme
await client.setEx('temp_data', 300, JSON.stringify(data)); // 5 dakika
// Pattern matching ile toplu silme
const keys = await client.keys('user:*');
if (keys.length > 0) {
await client.del(keys);
}
// Tag-based cache invalidation
const taggedCache = {
set: async (key, value, tags = [], ttl = 3600) => {
await client.setEx(key, ttl, JSON.stringify(value));
// Tag'lere key'i ekle
for (const tag of tags) {
await client.sAdd(`tag:${tag}`, key);
}
},
invalidateByTag: async (tag) => {
const keys = await client.sMembers(`tag:${tag}`);
if (keys.length > 0) {
await client.del(keys);
await client.del(`tag:${tag}`);
}
}
};
// Cache hit rate tracking
const cacheStats = {
hits: 0,
misses: 0,
getHitRate: () => {
const total = cacheStats.hits + cacheStats.misses;
return total > 0 ? (cacheStats.hits / total * 100).toFixed(2) : 0;
}
};
const getCachedDataWithStats = async (key) => {
const data = await client.get(key);
if (data) {
cacheStats.hits++;
return JSON.parse(data);
} else {
cacheStats.misses++;
return null;
}
};
// Redis INFO komutu ile durum kontrolü
const getRedisInfo = async () => {
const info = await client.info();
return info;
};
# docker-compose.yml
version: '3.8'
services:
redis:
image: redis:7-alpine
restart: always
ports:
- "6379:6379"
volumes:
- redis_data:/data
- ./redis.conf:/usr/local/etc/redis/redis.conf
command: redis-server /usr/local/etc/redis/redis.conf
app:
build: .
depends_on:
- redis
environment:
- REDIS_URL=redis://redis:6379
volumes:
redis_data:
Redis ve diğer cache teknolojileri ile web sitenizin performansını optimize edelim.
Ücretsiz Konsültasyon Hizmetlerimiz