php-redis - Is there a way to store PHP object in Redis without serializing it?

前端 未结 4 825
我寻月下人不归
我寻月下人不归 2021-02-14 17:10

I am trying to store user\' request URL as the key and a PHP object corresponding to that key as the value in Redis. I tried the following:

$redisClient = new Re         


        
4条回答
  •  天涯浪人
    2021-02-14 17:41

    Here is how I do it:

    class Cache extends Predis\Client {
        protected $prefix = 'myapp:';
    
        public function take($key, $value = null, $ttl = null) {
            $value = is_object($value) ? serialize($value) : $value;
            $key   = $this->prefix . $key;
            if (!$this->exists($key)) {
                if (intval($ttl)) {
                    $this->setEx($key, $ttl, $value);
                } else {
                    $this->set($key, $value);
                }
            }
            return $this->get($key);
        }
    }
    

    Usage:

    $cache = new Cache;
    
    $lorem     = 'Lorem ipsum dolor sit amet';
    $loremLong = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
    
    $cachedLorem          = $cache->take('lorem', $lorem);
    $cachedLoremLong      = $cache->take('loremLong', $loremLong);
    $cachedLoremTtl       = $cache->take('loremTtl', $lorem, 30);
    $cachedLoremGet       = $cache->take('lorem');
    $cachedLoremObject    = $cache->take('loremObject', new stdClass);
    $cachedLoremObjectTtl = $cache->take('loremObjectTtl', new stdClass, 45);
    
    echo $cachedLorem;
    echo $cachedLoremLong;
    echo $cachedLoremTtl;
    echo $cachedLoremGet;
    echo $cachedLoremObject;
    echo $cachedLoremObjectTtl;
    

    Output:

    Lorem ipsum dolor sit amet
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    Lorem ipsum dolor sit amet
    Lorem ipsum dolor sit amet
    O:8:"stdClass":0:{}
    O:8:"stdClass":0:{}
    

提交回复
热议问题