redis-patterns
ما الذي تفعله
يساعدك هذا الدليل على استخدام Redis، وهي قاعدة بيانات سريعة، في المهام البرمجية الشائعة. يوضح كيف تخزّن البيانات بكفاءة لتسريع تطبيقاتك، وتتحكم في الوصول، وترسل الرسائل.
متى تستخدمها
- ✓عندما تريد أن يصبح تطبيقك أسرع باستخدام التخزين المؤقت (caching).
- ✓لتحديد عدد مرات قيام المستخدم بعمل معين خلال فترة زمنية محددة.
- ✓للتأكد من أن جزءًا واحدًا فقط من الكود يعمل في الوقت نفسه.
رابط المهارة
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/redis-patterns/SKILL.mdانسخه والصقه في الذكاء الاصطناعي الذي تستخدمه (Claude أو ChatGPT أو Cursor) واطلب منه اتباع التعليمات.
طريقة الاستخدام
أسهل طريقة: انسخ الرسالة والصقها في الذكاء الاصطناعي الذي تستخدمه. سيقرأ المهارة وينفّذ تعليماتها.
رسالة جاهزة للصق
لـ Claude Code أو Codex أو Cursor: شغّله داخل مجلد مشروعك وستُثبَّت المهارة.
نزّل ملف SKILL.md وضعه في مجلد مهارات وكيلك.
مثال على ما تطلبه من الذكاء الاصطناعي
“كيف أستخدم Redis لتخزين معلومات جلسة المستخدم بأمان؟”
5 مهارات جديدة كل أسبوع. قراءة في دقيقة واحدة.
كيف تعمل
تستخدم هياكل بيانات Redis مثل النصوص والتجزئات (hashes) لحفظ المعلومات. وفي المهام الأكثر تعقيدًا، قد تستخدم سكربتات خاصة أو معاملات لضمان حدوث كل شيء بشكل صحيح.
المحتوى التقني (ملف SKILL.md الأصلي)
النص الأصلي من المؤلف، مباشرة من GitHub.
Redis Patterns
Quick reference for Redis best practices across common backend use cases.
How It Works
Redis is an in-memory data structure store that supports strings, hashes, lists, sets, sorted sets, streams, and more. Individual Redis commands are atomic on a single instance; multi-step workflows require Lua scripts, MULTI/EXEC transactions, or explicit synchronization to stay atomic. Data is optionally persisted via RDB snapshots or AOF logs. Clients communicate over TCP using the RESP protocol; connection pools are essential to avoid per-request handshake overhead.
When to Activate
- Adding caching to an application
- Implementing rate limiting or throttling
- Building distributed locks or coordination
- Setting up session or token storage
- Using Pub/Sub or Redis Streams for messaging
- Configuring Redis in production (pooling, eviction, clustering)
Data Structure Cheat Sheet
| Use Case | Structure | Example Key |
|---|---|---|
| Simple cache | String | product:123 |
| User session | Hash | session:abc |
| Leaderboard | Sorted Set | scores:weekly |
| Unique visitors | Set | visitors:2024-01-01 |
| Activity feed | List | feed:user:456 |
| Event stream | Stream | events:orders |
| Counters / rate limits | String (INCR) | ratelimit:user:123 |
| Bloom filter / HLL | HyperLogLog | hll:pageviews |
Core Patterns
Cache-Aside (Lazy Loading)
import redis
import json
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
def get_product(product_id: int):
cache_key = f"product:{product_id}"
cached = r.get(cache_key)
if cached:
return json.loads(cached)
product = db.query("SELECT * FROM products WHERE id = %s", product_id)
r.setex(cache_key, 3600, json.dumps(product)) # TTL: 1 hour
return product
Write-Through Cache
def update_product(product_id: int, data: dict):
# Write to DB first
db.execute("UPDATE products SET ... WHERE id = %s", product_id)
# Immediately update cache
cache_key = f"product:{product_id}"
r.setex(cache_key, 3600, json.dumps(data))
Cache Invalidation
# Tag-based invalidation — group related keys under a set
def cache_product(product_id: int, category_id: int, data: dict):
key = f"product:{product_id}"
tag = f"tag:category:{category_id}"
pipe = r.pipeline(transaction=True)
pipe.setex(key, 3600, json.dumps(data))
pipe.sadd(tag, key)
pipe.expire(tag, 3600)
pipe.execute()
def invalidate_category(category_id: int):
tag = f"tag:category:{category_id}"
keys = r.smembers(tag)
if keys:
r.delete(*keys)
r.delete(tag)
Session Storage
import time
import uuid
def create_session(user_id: int, ttl: int = 86400) -> str:
session_id = str(uuid.uuid4())
key = f"session:{session_id}"
pipe = r.pipeline(transaction=True)
pipe.hset(key, mapping={
"user_id": user_id,
"created_at": int(time.time()),
})
pipe.expire(key, ttl)
pipe.execute()
return session_id
def get_session(session_id: str) -> dict | None:
data = r.hgetall(f"session:{session_id}")
return data if data else None
def delete_session(session_id: str):
r.delete(f"session:{session_id}")
Rate Limiting
Fixed Window (Simple)
def is_rate_limited(user_id: int, limit: int = 100, window: int = 60) -> bool:
key = f"ratelimit:{user_id}:{int(time.time()) // window}"
pipe = r.pipeline(transaction=True)
pipe.incr(key)
pipe.expire(key, window)
count, _ = pipe.execute()
return count > limit
Sliding Window (Lua — Atomic)
-- sliding_window.lua
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
if count < limit then
-- Use unique member (now + sequence) to avoid collisions within the same millisecond
local seq_key = key .. ':seq'
local seq = redis.call('INCR', seq_key)
redis.call('EXPIRE', seq_key, math.ceil(window / 1000))
redis.call('ZADD', key, now, now .. '-' .. seq)
redis.call('EXPIRE', key, math.ceil(window / 1000))
return 1
end
return 0
sliding_window = r.register_script(open('sliding_window.lua').read())
def allow_request(user_id: int) -> bool:
key = f"ratelimit:sliding:{user_id}"
…
الأسئلة الشائعة
ما هو Redis؟
Redis قاعدة بيانات تخزّن المعلومات في ذاكرة الحاسوب لتوفر وصولًا سريعًا جدًا. وتدعم أنواعًا متعددة من البيانات، مثل النصوص والقوائم والمجموعات.
لماذا أستخدم «مجمّعات الاتصال» (connection pools)؟
إنشاء اتصال جديد بـ Redis في كل مرة يحتاجه التطبيق قد يكون بطيئًا. أما مجمّعات الاتصال فتبقي الاتصالات جاهزة للاستخدام، فتوفر الوقت.
ما هي «الأقفال الموزعة» (distributed locks)؟
هي آليات تضمن أن تطبيقًا أو عملية واحدة فقط تصل إلى مورد مشترك في كل مرة، لمنع التعارض.
التفاصيل
الوصف الأصلي من المؤلف
Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub/sub, and connection management for production applications. Use when adding caching, a distributed lock, rate limiting, or pub/sub with Redis, or when key design needs review.
repo: affaan-m/ECC
الشعبية
- نجوم GitHub
- 280k
- الترتيب
- #240
- الترخيص
- MIT
- آخر تحديث
- 15/10/2026
التعليقات
- …
المزيد من المهارات من هذا المستودع
accessibility
280kيساعد وكيلك على بناء واجهات يستطيع الجميع استعمالها، ويضمن عمل المواقع والتطبيقات جيدًا لذوي الإعاقة، كالمكفوفين وذوي الحركة المحدودة.
agent-architecture-audit
280kيتأكد وكيلك من أن كل شيء يعمل بشكل صحيح، ويجد مشكلات أنظمة الذكاء الاصطناعي ويصلحها، ليؤدي كما هو متوقع.
agent-eval
280kيساعد وكيلك على مقارنة أدوات البرمجة بالذكاء الاصطناعي المختلفة، ويقيس أيها أسرع وأرخص وأكثر موثوقية لمهام محددة.
agent-harness-construction
280kيساعد وكيلك على فهم طريقة إنجاز المهام بشكل أفضل، عبر تحسين الأدوات والتعليمات التي يستعملها لزيادة فرص نجاحه.
مهارات مشابهة
shopify
260kيتيح لوكيلك قراءة بيانات متجر Shopify وتحديثها، مثل المنتجات والمخزون والطلبات والعملاء، عبر واجهة Shopify GraphQL API.
rest-graphql-debug
260kيساعد وكيلك على معرفة سبب فشل استدعاء API من نوع REST أو GraphQL، بفحص الاتصال وتسجيل الدخول وصيغة الطلب والرد طبقة بعد طبقة.
har-derived-api-client
260kيساعد وكيلك على تسجيل حركة الشبكة لموقع إلكتروني مرة واحدة، ثم بناء عميل API مباشر له، فلا يعود إلى النقر في الصفحة في كل مرة.