php基于redis处理session的方法
2019/6/27 22:30:55
本文主要是介绍php基于redis处理session的方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一个基于redis的处理session的方法,如下。
<?php class Session_custom { private $redis; // redis实例 private $prefix = 'sess_'; // session_id前缀 // 会话开始时,会执行该方法,连接redis服务器 public function open($path, $name) { $this->redis = new Redis(); return $this->redis->connect("127.0.0.1",6379); } // 会话结束时,调用该方法,关闭redis连接 public function close() { $this->redis->close(); return true; } // 会话保存数据时调用该方法,在脚本执行完或session_write_close方法调用之后调用 public function write($session_id, $data) { return $this->redis->hMSet($this->prefix.$session_id, array('expires' => time(), 'data' => $data)); } // 在自动开始会话或者通过调用 session_start() 函数手动开始会话之后,PHP 内部调用 read 回调函数来获取会话数据。 public function read($session_id) { if($this->redis->exists($this->prefix.$session_id)) { return $this->redis->hGet($this->prefix.$session_id, 'data'); } return ''; } // 清除会话中的数据,当调用session_destroy()函数,或者调用 session_regenerate_id()函数并且设置 destroy 参数为 TRUE 时,会调用此回调函数。 public function destroy($session_id) { if($this->redis->exists($this->prefix.$session_id)) { return $this->redis->del($this->prefix.$session_id) > 0 ? true : false; } return true; } // 垃圾回收函数,调用周期由 session.gc_probability 和 session.gc_divisor 参数控制 public function gc($maxlifetime) { $allKeys = $this->redis->keys("{$this->prefix}*"); foreach($allKeys as $key) { if($this->redis->exists($key) && $this->redis->hGet($key, 'expires') + $maxlifetime < time()) { $this->redis->del($key); } } return true; } } // 调用自定义的session处理方法 $handler = new Session_custom(); session_set_save_handler( array($handler, 'open'), array($handler, 'close'), array($handler, 'read'), array($handler, 'write'), array($handler, 'destroy'), array($handler, 'gc') ); // 下面这行代码可以防止使用对象作为会话保存管理器时可能引发的非预期行为,表示当脚本执行之后或调用exit()之后,存储当前会话数据并关闭当前会话 register_shutdown_function('session_write_close'); session_start(); // 可以使用session了
补充:
php.ini文件中的session.gc_probability与session.gc_divisor两个配置选项共同决定gc函数调用的时机。默认值分为为1和1000,表示每个请求只有1/1000的机会调用gc函数。
以上就是本文的全部内容,希望对大家的学习有所帮助。
这篇关于php基于redis处理session的方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09vue3开发前端表单缓存自定义指令,移动端h5必备插件
- 2024-05-09React Hooks在class组件中的使用方式
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist
- 2024-03-11icons for vue
- 2024-03-07breadcrumbs react js
- 2024-03-06react login page example
- 2024-03-06react router uselocation
- 2024-03-04postgres jsonb_set