| Redis is an open-source, in-memory data structure store, used as a database, cache, and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, geospatial indexes, and streams, allowing for flexible data modeling and efficient retrieval. Its in-memory nature provides extremely fast read and write speeds, making it ideal for applications requiring high performance and low latency. 
To use Redis in Python, you'll need to install the redis library (now called redis-py) and then connect to your Redis server to perform operations. Here's a step-by-step guide with an example:
Install Redis LibraryYou can install the library using pip: pip install redis
Example: Basic Usage of Redis in Pythonimport redis
# Connect to Redis server
client = redis.StrictRedis(
host='localhost', # Replace with your Redis server host (default: 'localhost')
port=6379, # Redis server port (default: 6379)
db=0, # Redis database index (default: 0)
decode_responses=True # Automatically decode string responses
)
# Set a key-value pair
client.set('name', 'Alice')
# Get the value of a key
value = client.get('name')
print(f"The value of 'name' is: {value}")
# Increment a key
client.set('counter', 0) # Initialize counter
client.incr('counter') # Increment by 1
print(f"The value of 'counter' is: {client.get('counter')}")
# Delete a key
client.delete('name')
# Check if a key exists
exists = client.exists('name')
print(f"Does 'name' exist? {bool(exists)}")
# Add to a list
client.rpush('tasks', 'task1', 'task2', 'task3')
# Retrieve the list
tasks = client.lrange('tasks', 0, -1)
print(f"Tasks list: {tasks}")
# Remove all keys in the database
client.flushdb()
print("Database cleared.")
Explanation of Key Functions:set(key, value): Store a key-value pair.get(key): Retrieve the value associated with a key.incr(key): Increment the value of a key (useful for counters).delete(key): Delete a key from Redis.exists(key): Check if a key exists.rpush(key, *values): Push elements to the end of a list.lrange(key, start, end): Get a range of elements from a list.flushdb(): Remove all keys from the current database.
Running Redis ServerEnsure that a Redis server is running locally or remotely before executing the code. You can start a Redis server with: redis-server
This basic example demonstrates Redis as a key-value store, but Redis also supports other data structures like hashes, sets, and sorted sets. Let me know if you'd like more advanced examples!
Methods to Set Expiration:Using the expire Method Set an expiration time (in seconds) after creating a key. client.set('temp_key', 'temporary_value')
client.expire('temp_key', 10) # Expire after 10 seconds
Setting Expiration When Creating a Key Use the ex (seconds) or px (milliseconds) parameter when using set. client.set('temp_key', 'temporary_value', ex=10) # Expires after 10 seconds
client.set('temp_key_ms', 'temporary_value', px=5000) # Expires after 5000ms (5 seconds)
Using setex Method Combines setting a key and expiration in a single step. client.setex('temp_key', 10, 'temporary_value') # Set value with 10 seconds expiration
Example Code with Expiration:import redis
import time
# Connect to Redis
client = redis.StrictRedis(
host='localhost',
port=6379,
db=0,
decode_responses=True
)
# Set a key with an expiration time
client.set('temp_key', 'temporary_value', ex=5) # Expires in 5 seconds
print(f"temp_key: {client.get('temp_key')}")
# Wait for 6 seconds
time.sleep(6)
# Try to get the key after expiration
value = client.get('temp_key')
print(f"temp_key after expiration: {value}") # Should print None
Useful Expiration-Related Commands:ttl(key): Check the remaining time-to-live (TTL) of a key (in seconds). Returns -1 if no expiration is set and -2 if the key doesn't exist.
ttl = client.ttl('temp_key')
print(f"Time-to-live for temp_key: {ttl} seconds")
persist(key): Remove the expiration from a key, making it permanent.
client.persist('temp_key')
|