Redis In-Depth: From Basics to API Caching with Django
Redis vs. Memcached
Redis supports multipel data structures: strings, lists, hashes, sets, and sorted sets, whereas Memcached only handles strings. Redis also offers persistence and high concurrency; Memcached lacks persistence and has lower scalability.
Essential Redis Commands
# Start Redis background service with a config file
redis-server --service-start /d/Redis/my_redis.conf
# Connect to Redis
redis-cli -h localhost -p 6379 -n 0 -a your_password
# Shutdown the server
redis-cli shutdown
# Switch database
select 1
# Set a password (resets after restart to the config file value)
config set requirepass new_password
Data Persistence
- Automatic save on shutdown: Redis persists data to
dump.rdbby default. Location is configurable in the configuration file. - Periodic snapshots: Triggered by conditions defined in the config file (e.g., save 900 1).
- Manual save: Run
saveorbgsave.
Data Structures and Operations
String Operations
mset key1 value1 key2 value2 key3 value3
mget key1 key2 key3
setex temp_key 10 'temp_value' # Expires in 10 seconds
incrby counter 5
append my_str ' appended'
List Operations
rpush mylist item1 item2
lrange mylist 0 -1
llen mylist
ltrim mylist 1 3 # Keep only elements in index range 1-3
Hash Operations
hset user name 'Alice' age 30 gender 'F'
hmset user name 'Bob' age 25
hkeys user
hvals user
hdel user gender
Set Operations
sadd set1 a b c
scard set1
sinter set1 set2 # Intersection for mutual followers
sdiff set1 set2 # Difference for data comparison
sdiffstore result set1 set2 # Store difference into result
Sorted Set (Leaderboard)
zadd leaderboard 100 player1 200 player2 150 player3
zcount leaderboard 100 150
zincrby leaderboard 50 player1
zrange leaderboard 0 -1 # Ascending order
zrevrange leaderboard 0 1 # Top two players by descending score
Application: Game renkings, trending topics.
Python Redis Integration
import redis
pool = redis.ConnectionPool(
host='127.0.0.1',
port=6379,
db=1,
password=None,
decode_responses=True,
max_connections=10
)
r = redis.Redis(connection_pool=pool)
# Now use r.set(), r.get(), etc.
Django Cache with Redis
Configure django-redis to store cache and custom objects in Redis.
# settings.py
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100},
"DECODE_RESPONSES": True,
"PASSWORD": "",
}
}
}
# In a script
import os
import django
from django.core.cache import cache
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
django.setup()
from myapp.models import User
user_queryset = User.objects.all()
cache.set('users_cache', user_queryset, 300)
print(cache.get('users_cache'))
API Caching Example
Cache API responses for frequently accessed, non-real-time data to reduce database load.
# views.py
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from django.core.cache import cache
from . import models, serializers
class BannerListAPIView(ListAPIView):
queryset = models.Banner.objects.filter(is_deleted=False, is_active=True).order_by('-priority')[:10]
serializer_class = serializers.BannerSerializer
def list(self, request, *args, **kwargs):
cached_data = cache.get('banners')
if cached_data is None:
response = super().list(request, *args, **kwargs)
cache.set('banners', response.data, timeout=60*5)
return response
return Response(cached_data)