Using Redis as a Database: Python Code Samples and Comparison with MySQL
This article provides Python code examples for using Redis as a database—including connection, basic CRUD, list and sorted set operations, key expiration, publishing/subscribing, distributed locking, and caching—followed by a detailed comparison of Redis and MySQL across data model, persistence, query capabilities, performance, scalability, and transaction support.
When using Redis as a database, the following basic code examples illustrate how to 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 list tail
r.rpush('mylist', 'element1')
r.rpush('mylist', 'element2')
# Get elements in 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 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 (seconds)
r.expire('key', 60)
# Delete key
r.delete('key')Redis also supports more advanced use cases, such as messaging and distributed coordination.
1. Publish and subscribe messages:
import redis
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, 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):
data = r.get(key)
if data is not None:
print('Data retrieved from cache')
return data
# Simulate fetching from database
data = 'Data from database'
r.set(key, data)
r.expire(key, 3600) # 1 hour
print('Data retrieved from database')
return data
result = get_data_from_cache('mydata')
print(result)Redis and MySQL are two different types of databases; while Redis can replace MySQL in certain scenarios, it cannot fully replace a relational database.
Data model: Redis is a key‑value store with simple structures; MySQL is a relational DB with tables, rows, and complex schemas.
Persistence: Redis offers snapshot and append‑only file persistence, which is simpler than MySQL’s robust transactional storage.
Query language: MySQL uses SQL for powerful queries and joins; Redis provides command‑based access without a full query language.
Performance & scalability: Redis excels at low‑latency, high‑concurrency workloads; MySQL handles large data sets and complex queries with better scalability.
Transaction support: MySQL provides ACID transactions; Redis offers limited, optimistic‑lock‑based transactions without full ACID guarantees.
In summary, the choice between Redis and MySQL should be driven by the specific requirements of the application, and the two can often be combined to leverage the strengths of each.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.