设为首页 收藏本站
查看: 1064|回复: 0

[经验分享] 使用redis接管cookie

[复制链接]

尚未签到

发表于 2017-12-21 10:20:14 | 显示全部楼层 |阅读模式
使用redis接管cookie
class RedisCookie {// 默认配置名称(使用load_config加载)private $_default_config_path = 'package/cache/redis_cookie';// 当前用作服务端保存cookie数据的哈希名private $_cookie_id = null;    // cookie中的每个变量(包含cookie_id本身), 在redis中的最大生存时间    public $max_life_time = 0;    // 用作生成 cookie_id 的标识值    public $key_preffix = '';    // 客户端cookie_id的变量名    public $id_client_var = '';    // 客户端cookie_id的保存domain    public $id_client_host = '';    // cookie_id保存于客户端时的有效时长,单位:秒    public $id_valid_time = 0;    // \package\cache\Redis 类的一个实例    public $redis = null;     /**      * 构造函数     *      * @access public     * @param objcet $redis 指定一个特定的 \package\cache\Redis 实例     * @return void     */    public function __construct($redis=null) {        $conf = load_config($this -> _default_config_path);        if (!is_array($conf) or empty($conf)) {            to_log(MAIN_LOG_ERROR, '', __CLASS__ . ':' . __FUNCTION__ . ': 默认配置为空');            return;        }        isset($conf['max_life_time']) and $this -> max_life_time = $conf['max_life_time'];        isset($conf['key_preffix']) and $this -> key_preffix = $conf['key_preffix'];        isset($conf['id_client_var']) and $this ->>        isset($conf['id_client_host']) and $this ->>        isset($conf['id_valid_time']) and $this ->>        empty($redis) and $redis = g('\\package\\cache\\Redis');        $this -> redis = $redis;    }    /**     * 类似 session_start, 使用该类时调用这个方法初始化     *     * @access public     * @return void     */    public function start() {        $this -> get_now_id();    }    /**     * 获取cookie_id     *     * @access public     * @param integer $id 指定使用该id作为cookie_id     * @return string     */    public function get_now_id($id='') {        if (!empty($id)) {            $this -> _cookie_id = $id;            $this -> save_id();            $cookie_id = $id;        }else {            $cookie_id = $this -> get_id();        }        return $cookie_id;    }    /**     * 获取指定cookie数据     *     * @access public     * @param string $name 变量名     * @return mixed 失败返回(bool)false,否则返回(string)     */    public function get($name='') {        $name = strval($name);        $hash = $this -> get_now_id();        if (empty($name) or empty($hash)) {            return false;        }        $key = $this -> get_cache_key($name);        try {            $redis = $this -> redis -> get_handler();            $ret = $redis -> hGet($hash, $key);        }catch(\RedisException $e) {            return false;        }        if ($ret === false) return false;         $ret = json_decode($ret, true);        if (!is_array($ret) or empty($ret)) return false;        if ($ret['ttl'] <= time()) {            $this -> delete($key);            return false;        }        $this -> renew();        $ret = $ret['data'];        return $ret;    }    /**     * 设置指定cookie数据     *     * @access public     * @param string $name 缓存变量名     * @param mixed $value 缓存变量值     * @param string $ttl 有效的生存时间     * @return boolean     */    public function set($name, $value, $ttl=3600) {        $name = strval($name);        $hash = $this -> get_now_id();        if (empty($name) or empty($hash)) {            return false;        }        // 生存时间不能大于最大生存时间        $real_ttl = $ttl <= $this -> max_life_time ? $ttl : $this -> max_life_time;        $eff_end = time() + $real_ttl;        $cache_data = array(            'data' => $value,            'ttl' => $eff_end,        );        $key = $this -> get_cache_key($name);        $json_data = json_encode($cache_data);        try {            $redis = $this -> redis -> get_handler();            $ret = $redis -> hSet($hash, $key, $json_data);        }catch(\RedisException $e) {            return false;        }        if ($ret === false) return $ret;        $this -> renew();        return true;    }    /**     * 检测cookie_id是否已经被初始化     *     * @access public     * @return boolean     */    public function check_id_exists() {        if (isset($_COOKIE[$this ->>            return true;        }        return false;    }    /**     * 删除指定名称的cookie变量     *     * @access public     * @param string $name 变量名     * @return boolean     */    public function delete($name='') {        $name = strval($name);        $hash = $this -> get_now_id();        if (empty($name) or empty($hash)) {            return false;        }        $key = $this -> get_cache_key($name);        try {            $redis = $this -> redis -> get_handler();            $ret = $redis -> hDel($hash, $key);        }catch(\RedisException $e) {            return false;        }        return $ret;    }    /**     * 删除该cookie_id下的全部数据     *     * @access public     * @return boolean     */    public function destory() {        $hash = $this -> get_now_id();        if (empty($hash)) return false;        $this -> redis -> delete($hash);        $this -> _cookie_id = null;        setcookie($this ->>        return true;    }    /**     * 获取或构造cookie_id(不存在时)     *     * @access private     * @return string     */    private function get_id() {        if (!empty($this -> _cookie_id)) {            return $this -> _cookie_id;        }         if (isset($_COOKIE[$this ->>            $this -> _cookie_id = $_COOKIE[$this ->>        }else {            $this -> _cookie_id = $this -> create_id();            //保存cookie_id到客户端            $this -> save_id();        }        return $this -> _cookie_id;    }    /**     * 保存rcookie_id到客户端     *     * @access public     * @return void     */    private function save_id() {        setcookie($this ->>    }    /**     * 刷新cookie_id的生存时间     *     * @access private     * @return boolean     */    private function renew() {        $hash = $this -> get_now_id();        if (empty($hash)) return false;        $ret = $this -> redis -> expire($hash, $this -> max_life_time);        return $ret;    }    /**     * 生成新的cookie_id     *     * @access private     * @return string     */    private function create_id() {        $time = time();        $uid = uniqid($this -> key_preffix, true);        $rand = get_rand_str(3);        $key_str = "rcookie_id:uid:{$uid}:time:{$time}:rand:{$rand}";        $key = sha1($key_str);        return $key;    }    /**     * 获取redis缓存变量名     *     * @access private     * @param string $str 用作生成缓存变量的字符串     * @return string     */    private function get_cache_key($str) {        $key = md5($str);        return $key;    }}  posted on 2017-05-06 13:32 官朝辉 阅读(...) 评论(...)  编辑 收藏

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-426372-1-1.html 上篇帖子: redis requires Ruby version >= 2.2.2问题 下篇帖子: centos7安装redis-4.0.1集群
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表