Databases 9 min read

Master Redis with Python: Core Operations, Pub/Sub, Distributed Locks, and Caching

Learn how to use Redis with Python for basic CRUD, list and sorted‑set manipulation, key expiration, Pub/Sub messaging, distributed locks, and caching, and understand when Redis is a suitable complement or alternative to MySQL based on data model, performance, and transaction needs.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Master Redis with Python: Core Operations, Pub/Sub, Distributed Locks, and Caching

When using Redis as a database, the following Python code demonstrates basic and advanced operations.

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)  # b'value'

# Hash operations
r.hset('hash_key', 'field', 'value')
hash_value = r.hget('hash_key', 'field')
print(hash_value)  # b'value'

3. List operations

# Append elements to a list
r.rpush('mylist', 'element1')
r.rpush('mylist', 'element2')

# Get list elements
elements = r.lrange('mylist', 0, -1)
print(elements)  # [b'element1', b'element2']

4. Sorted set operations

# Add members with scores
r.zadd('myzset', {'member1': 1, 'member2': 2, 'member3': 3})

# Retrieve members with scores
members = r.zrange('myzset', 0, -1, withscores=True)
print(members)  # [(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 a key
r.delete('key')

6. Publish/Subscribe messaging

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'])

7. 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')

8. Simple caching pattern

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 database fetch
    data = 'Data from database'
    r.set(key, data)
    r.expire(key, 3600)
    print('Data retrieved from database')
    return data

result = get_data_from_cache('mydata')
print(result)

Redis excels in high‑throughput, low‑latency scenarios such as caching, counters, and message queues, but it lacks the rich relational model, SQL query capabilities, and strong ACID transaction support of MySQL. Choosing between Redis and MySQL depends on data model complexity, persistence requirements, query needs, performance, scalability, and transaction guarantees.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythondatabaserediscachingdistributed-lockComparisonPubSub
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.