Using Redis as a Database: Basic Operations, Advanced Features, and Comparison with MySQL
This article demonstrates how to use Redis as a database with Python code examples for basic operations, advanced features like pub/sub and distributed locks, and compares Redis to MySQL across data model, persistence, query capabilities, performance, scalability, and transaction support.
When using Redis as a database, the article provides basic code examples that show how to connect, store, retrieve, and update data.
1. Connect to Redis server
import redis
# Create Redis connection
r = redis.Redis(host='localhost', port=6379, db=0)2. Store and retrieve data
# Store data
r.set('key', 'value')
# Retrieve data
value = r.get('key')
print(value) # output: b'value'
# Store and retrieve hash data
r.hset('hash_key', 'field', 'value')
hash_value = r.hget('hash_key', 'field')
print(hash_value) # output: b'value'3. List operations
# Append elements to the tail of a list
r.rpush('mylist', 'element1')
r.rpush('mylist', 'element2')
# Get elements in a range
elements = r.lrange('mylist', 0, -1)
print(elements) # output: [b'element1', b'element2']4. Sorted set operations
# Add members with scores
r.zadd('myzset', {'member1': 1, 'member2': 2, 'member3': 3})
# Get members in a range with scores
members = r.zrange('myzset', 0, -1, withscores=True)
print(members) # output: [(b'member1', 1.0), (b'member2', 2.0), (b'member3', 3.0)]5. Key expiration and deletion
# Set expiration time (seconds)
r.expire('key', 60)
# Delete a key
r.delete('key')More complex examples illustrate advanced Redis usage.
1. Publish/Subscribe messaging
import redis
# Create Redis connection
r = redis.Redis(host='localhost', port=6379, db=0)
# Publish a message
r.publish('channel', 'message')
# Subscribe to a channel
pubsub = r.pubsub()
pubsub.subscribe('channel')
for item in pubsub.listen():
if item['type'] == 'message':
print(item['channel'], item['data'])2. Implement a distributed lock
import redis
import time
r = redis.Redis(host='localhost', port=6379, db=0)
def acquire_lock(lock_name, acquire_timeout=10):
lock = False
end_time = time.time() + acquire_timeout
while time.time() < end_time and not lock:
lock = r.setnx(lock_name, 'locked')
if lock:
r.expire(lock_name, acquire_timeout)
return lock
def release_lock(lock_name):
r.delete(lock_name)
if acquire_lock('mylock'):
try:
print('Executing critical section...')
finally:
release_lock('mylock')
else:
print('Could not acquire lock')3. Use Redis as a cache
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
def get_data_from_cache(key):
# Try to get data from cache
data = r.get(key)
if data is not None:
print('Data retrieved from cache')
return data
# Simulate fetching from database
data = 'Data from database'
# Store in cache with 1‑hour expiration
r.set(key, data)
r.expire(key, 3600)
print('Data retrieved from database')
return data
result = get_data_from_cache('mydata')
print(result)Redis and MySQL are different types of databases; while Redis can replace MySQL in certain scenarios, it cannot fully substitute a relational database.
Data model : Redis is a key‑value in‑memory store with simple structures (strings, lists, hashes, sorted sets). MySQL is a relational DB supporting complex tables, rows, and columns.
Persistence : Redis offers snapshot and append‑only file persistence, which is simpler than MySQL’s robust disk storage and transaction logs.
Query language : MySQL uses SQL for powerful queries and aggregations; Redis provides command‑based access without a full query language.
Scale and performance : Redis excels at low‑latency, high‑concurrency workloads on small to medium data sets; MySQL scales better for large data sets and complex queries.
ACID transactions : MySQL provides full ACID compliance; Redis offers limited, optimistic‑lock‑based transactions without strict ACID guarantees.
Although Redis can replace MySQL in specific use cases such as caching, counters, or message queues, it is not suitable for all scenarios. Choose the appropriate database based on the requirements, or combine both technologies.
Further detailed considerations include data model flexibility, persistence reliability, query capabilities, performance, scalability, and transaction support.
Data model and flexibility : MySQL’s relational schema allows complex relationships; Redis’s simpler model may limit complex data handling.
Persistence and reliability : MySQL provides multiple durable storage options; Redis’s persistence is simpler and may risk data loss on failure.
Query language and functionality : MySQL’s SQL offers rich querying; Redis’s command set is limited for complex queries.
Performance and scalability : Redis delivers high performance for in‑memory operations; MySQL handles large datasets with proper indexing and optimization.
Transaction support : MySQL guarantees ACID transactions; Redis’s transactions are optimistic and lack full atomicity.
In summary, Redis and MySQL differ in data model, flexibility, persistence, query language, performance, scalability, and transaction support; choose based on application needs and consider combining them when appropriate.
Backend Community Invitation
Build a high‑quality technical exchange community; developers, recruiters, and anyone interested in sharing job referrals are welcome to join and help each other improve.
Maintain civility, focusing on technical discussion , job referrals , and industry exploration .
Advertisements are prohibited; do not trust private messages to avoid scams.
Contact me to be added to the group.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.