SncRedisBundle

repository·master·Indexed 21 days ago

https://github.com/snc/sncredisbundle

A Symfony bundle providing a convenient interface to Redis by integrating the native PhpRedis extension, the Predis library, or relay. It supports various configurations including Master-Slave replication, Sentinel, Redis Cluster, and client-side sharding (RedisArray). The bundle includes integrations for Symfony sessions, Monolog logging, and Symfony Cache Pools, as well as a `redis:query` CLI command for executing arbitrary Redis commands.

Tokens
6.3K
Snippets
21
Records
24
Agent score
76%

What's inside SncRedisBundle

  1. Supported Redis clients in SncRedisBundle

    master

    SncRedisBundle provides an interface to Redis by integrating two different PHP clients:

    1. PhpRedis: The native PHP extension. This is the recommended client as it is faster and the primary development platform for the bundle.
    2. Predis: A pure PHP implementation. Use this as a portable alternative if the PhpRedis extension cannot be installed in your environment. The integration is designed to be functionally identical to PhpRedis.
  2. Use Persistent Connections

    master

    Persistent connections can be enabled via the connection_persistent option. This is critical when multiple clients connect to different databases on the same Redis server to prevent them from sharing the same socket and context.

    connection_persistent accepts:

    • true: Uses the client alias as the connection ID.
    • false: Disables persistent connections (default).
    • string: Uses the provided string as the connection ID.

    Driver behavior:

    • phpredis: The ID is passed to pconnect().
    • predis: The ID is mapped to conn_uid (requires predis/predis >= 2.4.0).
    snc_redis:
        clients:
            app_cache:
                type: predis
                alias: app_cache
                dsn: redis://localhost/0
                options:
                    connection_persistent: "app_cache_connection"
            session_store:
                type: predis
                alias: session_store
                dsn: redis://localhost/1
                options:
                    connection_persistent: true
  3. Migrate from RedisBundle 3.x to 4.0.0

    master

    When upgrading to version 4.0.0, several features and integrations have been removed. Ensure you address the following changes in your application:

    • Session Management: The built-in session integration is removed. Follow the official Symfony guide to store sessions in a Redis key-value database.
    • Rate Limiting: The RateLimit class is removed. Replace it with symfony/rate-limiter.
    • Doctrine Integration: Doctrine integration is removed. Configure your cache pools via framework.yaml and follow the doctrine-bundle documentation to configure Doctrine to use those pools.
    • Profiler Storage: The snc_redis.profiler_storage configuration option has been removed.
    • PHP Redis Connection Wrappers: The class.phpredis_connection_wrapper and class.phpredis_clusterclient_connection_wrapper configuration options are no longer available.
    • Dependencies: If you have logging enabled for the phpredis client, you must now require either ocramius/proxy-manager or friendsofphp/proxy-manager-lts.
    • PHP Version: The minimum PHP requirement has increased from 7.2 to 7.4.
    • Type Safety: All functions now include return and parameter type declarations.
  4. Install RedisBundle

    master

    To install RedisBundle, add it to your composer.json file. If you intend to use the predis client library, you must also install the predis/predis package.

    1. Install the bundle:
    composer require snc/redis-bundle
    1. (Optional) Install Predis if needed:
    composer require predis/predis
    1. Register the bundle in your Symfony kernel:
    public function registerBundles()
    {
        $bundles = [
            // ...
            new Snc\RedisBundle\SncRedisBundle(),
            // ...
        ];
        ...
    }
    $ composer require snc/redis-bundle
  5. Configure Symfony Cache Pools with Redis

    master

    To use a Redis client for Symfony App Cache or specific Cache Pools, use the client's service name (e.g., snc_redis.default) as the provider in your cache configuration.

    framework:
        cache:
            app: cache.adapter.redis
            default_redis_provider: snc_redis.default
            pools:
                some-pool.cache:
                    adapter: cache.adapter.redis
                    provider: snc_redis.cache
  6. Configure Redis for Sessions

    master

    To use Redis for Symfony sessions, define a Redis client and then reference its service in your framework.yaml using the RedisSessionHandler.

    ```yaml
    # config/packages/snc_redis.yaml
    snc_redis:
        clients:
            session:
                type: predis
                alias: session
                dsn: redis://localhost/1
    
    # config/packages/framework.yaml
    framework:
        session:
            handler_id: Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler
    
    services:
        Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler:
            arguments: ['@snc_redis.session']

    Note: This implementation does not perform session locking and may be subject to race conditions.

  7. Configure Monolog with Redis

    master

    You can store Monolog logs in a Redis LIST. You must configure the Redis client with logging: false to prevent the logger from trying to log its own operations, and then define a Monolog handler that uses the client service.

    snc_redis:
        clients:
            monolog:
                type: predis
                alias: monolog
                dsn: redis://localhost/1
                logging: false
                options:
                    connection_persistent: true
        monolog:
            client: monolog
            key: monolog
    
    monolog:
        handlers:
            main:
                type: service
                id: snc_redis.monolog.handler
                level: debug
  8. Configure Redis clients

    master

    Configure one or more Redis clients in your config.yml under the snc_redis key. Each client requires a type (one of predis, phpredis, or relay), an alias, and a dsn.

    Important: Passwords containing special characters like @, %, :, or + in the DSN string must be URL-encoded.

    Services are available in the container as snc_redis.{alias}.

    snc_redis:
        clients:
            default:
                type: predis
                alias: default
                dsn: redis://localhost
  9. Configure Redis connection using a DSN

    master

    SncRedisBundle supports configuring Redis connections using a Data Source Name (DSN) string. The DSN follows the standard Redis URI format and can include credentials, host/socket information, database selection, and various query parameters.

    Supported URI Schemes

    • redis:// for standard connections.
    • rediss:// for TLS/SSL connections.

    DSN Components

    • Credentials: username:password@ (both are URL-encoded).
    • Host/Socket: A hostname, IP address (including IPv6 in []), or a Unix socket path starting with /.
    • Port: Specified after a colon (e.g., :6379).
    • Database: Specified as a path suffix (e.g., /0 or /my_db).
    • Query Parameters: Appended via ? to configure bundle-specific options.

    Supported Query Parameters

    ParameterDescription
    weightInteger weight for connection pooling/selection
    aliasAn alias for the connection
    roleThe Redis role (e.g., master, slave)
    prefixA key prefix to be applied to all keys
    tls_versionThe TLS version to use

    Examples

    Standard connection with password: redis://:password@127.0.0.1:6379/0

    TLS connection with username and password: rediss://user:password@redis.example.com:6379/0?tls_version=tlsv1.2

    Unix socket connection: redis:///var/run/redis/redis.sock?prefix=my_app_

    IPv6 connection: redis://[2001:db8::1]:6379/0

    redis://[user:password@]host[:port][/database][?param1=val1&param2=val2]
  10. Troubleshoot cache warmup failures in production

    master

    If cache warmup fails in a production environment because the Redis server is unavailable, it is likely because services are attempting to connect to Redis during the container compilation/warmup phase.

    You can resolve this by installing symfony/proxy-manager-bridge. This allows certain services to be lazy-loaded, preventing unwanted connection attempts to the Redis server during the warmup process.

    $ composer require symfony/proxy-manager-bridge
  11. Configure Predis Master-Slave replication

    master

    To set up master-slave replication using predis, provide an array of DSNs. The master connection must be tagged with the master role in its DSN for predis to function correctly.

    snc_redis:
        clients:
            default:
                type: predis
                alias: default
                dsn:
                    - redis://master-host?role=master
                    - redis://slave-host1
                    - redis://slave-host2
                options:
                    replication: predis