PHP将表中所有字段读取出来存到redis中



namespace app\index\controller;

require __DIR__ . '/../../../vendor/memcached/class/memcached.php';

class Index
{
    public static $memcached = false;
    public static $redis = false;

    public function __construct()
    {
        self::$memcached = $this->getMemcached();
        self::$redis = $this->getRedis();
    }

    public function index()
    {
        $res = model('Blog')->column('id,uid,title,content,image,view,created,updated');
        if ($res) {
            foreach ($res as $k => $v) {
                if (!self::$redis->exists('Blog:' . $k)) {
                    self::$redis->hMSet('Blog' . $k, $v);
                }
            }
        }
    }

    /***
     * @return bool|\memcached
     * 通过单例模式返回memcached对象
     */
    private function getMemcached()
    {
        if (self::$memcached) {
            return self::$memcached;
        } else {
            return self::$memcached = new \memcached(array(
                'servers' => array('127.0.0.1:11211'),
                'debug' => false,
                'compress_threshold' => 10240,
                'persistant' => true));
        }
    }

    /***
     * @return bool|\Redis
     * 通过单例模式返回redis对象
     */
    private function getRedis()
    {
        if (self::$redis) {
            return self::$redis;
        } else {
            self::$redis = new \Redis();
            self::$redis->connect('127.0.0.1', 6379);
            return self::$redis;
        }
    }
}

最后编辑于:2019/12/25作者: 牛逼PHP

发表评论