Redis example

/** * @param array $options associative array of options * * @throws Zend_Cache_Exception */
    public function __construct(array $options = [])
    {
        if (!extension_loaded('redis')) {
            Zend_Cache::throwException('The redis extension must be loaded for using this backend !');
        }
        parent::__construct($options);
        $this->_redis = new Redis();

        foreach ($this->_options['servers'] as $server) {
            if (!array_key_exists('port', $server)) {
                $server['port'] = self::DEFAULT_PORT;
            }
            if (!array_key_exists('host', $server)) {
                $server['host'] = self::DEFAULT_HOST;
            }
            if (!array_key_exists('persistent', $server)) {
                $server['persistent'] = self::DEFAULT_PERSISTENT;
            }
            
/** * Create a new cache object * * @param string $location Location string (from SimplePie::$cache_location) * @param string $name Unique ID for the cache * @param string $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data */
    public function __construct($location$name$options = null) {
        //$this->cache = \flow\simple\cache\Redis::getRedisClientInstance();         $parsed = SimplePie_Cache::parse_URL($location);
        $redis = new Redis();
        $redis->connect($parsed['host']$parsed['port']);
        if (isset($parsed['pass'])) {
            $redis->auth($parsed['pass']);
        }
        if (isset($parsed['path'])) {
            $redis->select((int)substr($parsed['path'], 1));
        }
        $this->cache = $redis;

        if (!is_null($options) && is_array($options)) {
            $this->options = $options;
        }
$factory = new RedisTransportFactory();
        $serializer = $this->createMock(SerializerInterface::class);
        $expectedTransport = new RedisTransport(Connection::fromDsn('redis://'.getenv('REDIS_HOST')['stream' => 'bar', 'delete_after_ack' => true])$serializer);

        $this->assertEquals($expectedTransport$factory->createTransport('redis://'.getenv('REDIS_HOST')['stream' => 'bar', 'delete_after_ack' => true]$serializer));
    }

    private function skipIfRedisUnavailable()
    {
        try {
            (new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
        } catch (\Exception $e) {
            self::markTestSkipped($e->getMessage());
        }
    }
}

    public function testCreateStore($connection, string $expectedStoreClass)
    {
        $store = StoreFactory::createStore($connection);

        $this->assertInstanceOf($expectedStoreClass$store);
    }

    public static function validConnections(): \Generator
    {
        if (class_exists(\Redis::class)) {
            yield [new \Redis(), RedisStore::class];
        }
        yield [new \Predis\Client(), RedisStore::class];
        if (class_exists(\Memcached::class)) {
            yield [new \Memcached(), MemcachedStore::class];
        }
        if (\extension_loaded('sysvsem')) {
            yield ['semaphore', SemaphoreStore::class];
        }
        if (class_exists(AbstractAdapter::class) && MemcachedAdapter::isSupported()) {
            yield ['memcached://server.com', MemcachedStore::class];
            yield ['memcached:?host[localhost]&host[localhost:12345]', MemcachedStore::class];
        }

class RedisArrayStoreTest extends AbstractRedisStoreTestCase
{
    public static function setUpBeforeClass(): void
    {
        if (!class_exists(\RedisArray::class)) {
            throw new SkippedTestSuiteError('The RedisArray class is required.');
        }
        try {
            (new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
        } catch (\Exception $e) {
            throw new SkippedTestSuiteError($e->getMessage());
        }
    }

    protected function getRedisConnection(): \RedisArray
    {
        $redis = new \RedisArray([getenv('REDIS_HOST')]);

        return $redis;
    }
}
$this->assertNotInstanceof(TagAwareAdapter::class$pool7);
    }

    protected static function createKernel(array $options = []): KernelInterface
    {
        return parent::createKernel(['test_case' => 'CachePools'] + $options);
    }

    private function skipIfRedisUnavailable()
    {
        try {
            (new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
        } catch (\Exception $e) {
            self::markTestSkipped($e->getMessage());
        }
    }
}

class RedisArrayStoreTest extends AbstractRedisStoreTestCase
{
    public static function setUpBeforeClass(): void
    {
        if (!class_exists(\RedisArray::class)) {
            throw new SkippedTestSuiteError('The RedisArray class is required.');
        }
        try {
            (new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
        } catch (\Exception $e) {
            throw new SkippedTestSuiteError($e->getMessage());
        }
    }

    protected function getRedisConnection(): \RedisArray
    {
        return new \RedisArray([getenv('REDIS_HOST')]);
    }
}
throw new RuntimeException(sprintf("Unable to write in the doctrine proxy directory (%s)\n", $dir));
        }

        parent::setProxyDir($dir);
    }

    /** * @return RedisCache */
    private function createRedisCacheProvider(array $options)
    {
        $redis = new Redis();
        if (isset($options['redisPersistent']) && $options['redisPersistent'] == true) {
            $redis->pconnect($options['redisHost']$options['redisPort']);
        } else {
            $redis->connect($options['redisHost']$options['redisPort']);
        }

        if (isset($options['redisAuth'])) {
            $redis->auth($options['redisAuth']);
        }

        $redis->select($options['redisDbIndex']);
        
$host$port] = $address;
                            }
                        } catch (\RedisException|\Relay\Exception $redisException) {
                        }
                    } while (++$hostIndex < \count($hosts) && !$address);

                    if (!$address) {
                        throw new InvalidArgumentException(sprintf('Failed to retrieve master information from sentinel "%s".', $sentinelMaster), previous: $redisException ?? null);
                    }
                }

                return self::initializeRedis($redis ?? (\extension_loaded('redis') ? new \Redis() : new Relay())$host$port$auth$options);
            };
        }

        if (!$options['lazy']) {
            $this->getRedis();
        }

        foreach (['stream', 'group', 'consumer'] as $key) {
            if ('' === $options[$key]) {
                throw new InvalidArgumentException(sprintf('"%s" should be configured, got an empty string.', $key));
            }
        }


namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

/** * @group integration */
class RedisSessionHandlerTest extends AbstractRedisSessionHandlerTestCase
{
    protected function createRedisClient(string $host): \Redis
    {
        $client = new \Redis();
        $client->connect(...explode(':', $host));

        return $client;
    }
}
abstract protected function createRedisClient(string $host): \Redis|Relay|\RedisArray|\RedisCluster|\Predis\Client;

    protected function setUp(): void
    {
        parent::setUp();

        if (!\extension_loaded('redis')) {
            self::markTestSkipped('Extension redis required.');
        }
        try {
            (new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
        } catch (\Exception $e) {
            self::markTestSkipped($e->getMessage());
        }

        $host = getenv('REDIS_HOST') ?: 'localhost';

        $this->redisClient = $this->createRedisClient($host);
        $this->storage = new RedisSessionHandler(
            $this->redisClient,
            ['prefix' => self::PREFIX]
        );
    }
$this->redis->close();
        }
    }

    /** * {@inheritDoc} */
    public function initialize()
    {
        $config = $this->config;

        $this->redis = new Redis();

        try {
            // Note:: If Redis is your primary cache choice, and it is "offline", every page load will end up been delayed by the timeout duration.             // I feel like some sort of temporary flag should be set, to indicate that we think Redis is "offline", allowing us to bypass the timeout for a set period of time.
            if ($this->redis->connect($config['host']($config['host'][0] === '/' ? 0 : $config['port'])$config['timeout'])) {
                // Note:: I'm unsure if log_message() is necessary, however I'm not 100% comfortable removing it.                 log_message('error', 'Cache: Redis connection failed. Check your configuration.');

                throw new CriticalError('Cache: Redis connection failed. Check your configuration.');
            }

            

class RedisStoreTest extends AbstractRedisStoreTestCase
{
    protected function setUp(): void
    {
        $this->getRedisConnection()->flushDB();
    }

    public static function setUpBeforeClass(): void
    {
        try {
            (new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
        } catch (\Exception $e) {
            throw new SkippedTestSuiteError($e->getMessage());
        }
    }

    protected function getRedisConnection(): \Redis
    {
        $redis = new \Redis();
        $redis->connect(...explode(':', getenv('REDIS_HOST')));

        return $redis;
    }

class RedisStoreTest extends AbstractRedisStoreTestCase
{
    use SharedLockStoreTestTrait;

    public static function setUpBeforeClass(): void
    {
        try {
            (new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
        } catch (\Exception $e) {
            throw new SkippedTestSuiteError($e->getMessage());
        }
    }

    protected function getRedisConnection(): \Redis
    {
        $redis = new \Redis();
        $redis->connect(...explode(':', getenv('REDIS_HOST')));

        return $redis;
    }
public function createCachePool(int $defaultLifetime = 0, string $testMethod = null): CacheItemPoolInterface
    {
        return new RedisAdapter(self::$redisstr_replace('\\', '.', __CLASS__)$defaultLifetime);
    }

    public static function setUpBeforeClass(): void
    {
        if (!\extension_loaded('redis')) {
            throw new SkippedTestSuiteError('Extension redis required.');
        }
        try {
            (new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
        } catch (\Exception $e) {
            throw new SkippedTestSuiteError(getenv('REDIS_HOST').': '.$e->getMessage());
        }
    }

    /** * @runInSeparateProcess */
    public function testClearWithPrefix()
    {
        $cache = $this->createCachePool(0, __FUNCTION__);

        
Home | Imprint | This part of the site doesn't use cookies.