Using Redis in Controllers

Redis provides powerful caching, session management, and data storage capabilities for your RouteMQ controllers. This guide shows how to integrate Redis operations in your controller methods.

Redis Manager

RouteMQ includes a built-in Redis manager that provides async operations with connection pooling and error handling.

Basic Usage

from core.controller import Controller
from core.redis_manager import redis_manager
import json

class CachedController(Controller):
    @staticmethod
    async def handle_data(device_id: str, payload, client):
        """Handle data with Redis caching"""
        cache_key = f"device:{device_id}:last_data"
        
        # Store data in Redis
        await redis_manager.set_json(cache_key, payload, ex=3600)  # 1 hour TTL
        
        # Process the data
        result = await CachedController.process_data(payload)
        
        return result

Configuration

Redis is configured through environment variables:

Basic Operations

String Operations

JSON Operations

Hash Operations

Advanced Patterns

Caching with Fallback

Rate Limiting

Session Management

Distributed Locking

Error Handling

Always handle Redis errors gracefully:

Performance Tips

1. Use Appropriate Expiration Times

2. Batch Operations

3. Connection Management

The Redis manager handles connection pooling automatically, but you can check connection status:

Next Steps

Last updated