Regular Text
Learn the fundamentals and find valuable information to get the most out of AWS.
Formatted Text
Code Text
cat > test_memorydb.py << EOF
import redis
import json
import sys
from datetime import datetime
# Check for command line argument
if len(sys.argv) != 2:
print("Usage: python3 test_memorydb.py <your-cluster-endpoint>")
print("Example: python3 test_memorydb.py memorydb-demo-cluster.abc123.memorydb.us-east-1.amazonaws.com")
sys.exit(1)
cluster_endpoint = sys.argv[1]
# Configure connection
try:
r = redis.Redis(
host=cluster_endpoint,
port=6379,
ssl=True,
decode_responses=True
)
# Test connection
r.ping()
print(f"✓ Successfully connected to MemoryDB cluster: {cluster_endpoint}")
except redis.ConnectionError as e:
print(f"✗ Failed to connect to {cluster_endpoint}")
print(f"Error: {e}")
print("\nPlease check:")
print(" - Cluster endpoint is correct")
print(" - Security group allows port 6379 from this instance")
print(" - Instance and cluster are in the same VPC")
sys.exit(1)
# Session management example
def create_session(user_id, username):
session_data = {
'user_id': user_id,
'username': username,
'login_time': datetime.now().isoformat()
}
# Store session with 30-minute expiration
r.setex(f'session:{user_id}', 1800, json.dumps(session_data))
print(f"✓ Session created for {username}")
def get_session(user_id):
session = r.get(f'session:{user_id}')
if session:
return json.loads(session)
return None
# Test the functions
print("\n--- Testing Session Management ---")
create_session('user001', 'alice')
session = get_session('user001')
print(f"✓ Retrieved session: {session}")
# Cache example with automatic expiration
print("\n--- Testing Cache with TTL ---")
r.setex('cache:api_response', 300, json.dumps({'data': 'cached response'}))
print(f"✓ Cache created with TTL: {r.ttl('cache:api_response')} seconds")
# Additional tests for data persistence
print("\n--- Testing Data Persistence ---")
r.set('persistent:data', 'This will survive a failover')
print(f"✓ Persistent data stored")
# Test various data structures
print("\n--- Testing Redis Data Structures ---")
# Hash
r.hset('user:1001', mapping={
'name': 'Alice',
'email': 'alice@example.com',
'lastLogin': datetime.now().isoformat()
})
print(f"✓ Hash created: {r.hgetall('user:1001')}")
# List
r.lpush('recent:logins', 'user001', 'user002', 'user003')
print(f"✓ List created: {r.lrange('recent:logins', 0, -1)}")
# Set
r.sadd('active:users', 'alice', 'bob', 'charlie')
print(f"✓ Set created with {r.scard('active:users')} members")
print("\n✓ All tests completed successfully!")
EOF