SessionRedis.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /*
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fecshop\services\session;
  10. use Yii;
  11. use fecshop\services\Service;
  12. //use fecshop\models\mysqldb\SessionStorage;
  13. /**
  14. * redis session services
  15. * @author Terry Zhao <2358269014@qq.com>
  16. * @since 1.0
  17. */
  18. class SessionRedis extends Service implements SessionInterface
  19. {
  20. protected $valSeparator = '||####||';
  21. public function init()
  22. {
  23. parent::init();
  24. }
  25. public function set($key, $val, $timeout)
  26. {
  27. $key = $this->getSessionKey($key);
  28. $val = $val . $this->valSeparator . time();
  29. return (bool) Yii::$app->redis->executeCommand('SET', [$key, $val, 'EX', $timeout]);
  30. }
  31. public function get($originKey, $reflush)
  32. {
  33. $key = $this->getSessionKey($originKey);
  34. $data = Yii::$app->redis->executeCommand('GET', [$key]);
  35. $arr = explode($this->valSeparator, $data);
  36. if (count($arr) < 2) {
  37. return '';
  38. }
  39. $val = $arr[0];
  40. $timeout = $arr[1];
  41. if (Yii::$service->session->isUpdateTimeOut($timeout) && $val) {
  42. $this->set($originKey, $val, $timeout);
  43. }
  44. return $val === false || $val === null ? '' : $val;
  45. }
  46. public function remove($key)
  47. {
  48. $key = $this->getSessionKey($key);
  49. Yii::$app->redis->executeCommand('DEL', [$key]);
  50. // @see https://github.com/yiisoft/yii2-redis/issues/82
  51. return true;
  52. }
  53. public function getSessionKey($key)
  54. {
  55. $uuid = Yii::$service->session->getUUID();
  56. return $uuid.'###^^###'.$key;
  57. }
  58. /**
  59. * 销毁所有
  60. */
  61. public function destroy()
  62. {
  63. }
  64. public function setFlash($key, $val, $timeout)
  65. {
  66. }
  67. public function getFlash($key)
  68. {
  69. }
  70. }