Redist.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. class Redist{
  3. public $expireTime;
  4. public $server;
  5. private $_redis;
  6. private static $_instance;
  7. function __construct(){
  8. if(!extension_loaded("redis") && Yii::app()->params["user_login_cache"]["state"] == "on")
  9. throw new Exception("Redis extension is not loaded");
  10. $this->expireTime = isset(Yii::app()->params["user_login_cache"]["expire_time"]) ? Yii::app()->params["user_login_cache"]["expire_time"] : 3600;
  11. $server = Yii::app()->params["user_login_cache"]["servers"];
  12. $this->_redis = new Redis();
  13. $this->_redis->connect($server["host"], $server["port"]);
  14. if(isset($server['password'])){
  15. $this->_redis->auth($server['password']);
  16. }
  17. $this->_redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);
  18. }
  19. protected static function instance(){
  20. if(!is_object(self::$_instance)){
  21. self::$_instance = new self();
  22. }
  23. return self::$_instance;
  24. }
  25. public static function select($dbNum){
  26. return self::instance()->_redis->select($dbNum);
  27. }
  28. public static function keys($keys){
  29. return self::instance()->_redis->keys($keys);
  30. }
  31. public static function set($key, $val){
  32. $params = func_get_args();
  33. if(isset($params[2]))
  34. $expireTime = $params[2];
  35. else
  36. $expireTime = self::instance()->expireTime;
  37. return $expireTime === -1 ? self::instance()->_redis->set($key, $val) : self::instance()->_redis->setex($key, $expireTime, $val);
  38. }
  39. public static function add($key, $val){
  40. $params = func_get_args();
  41. if(isset($params[2]))
  42. $expireTime = $params[2];
  43. else
  44. $expireTime = self::instance()->expireTime;
  45. try{
  46. self::instance()->_redis->multi();
  47. self::instance()->_redis->setnx($key, $val);
  48. self::instance()->_redis->expire($key, $expireTime);
  49. self::instance()->_redis->exec();
  50. return true;
  51. }
  52. catch(RedisException $e){
  53. return false;
  54. }
  55. }
  56. public static function exists($key){
  57. return self::instance()->_redis->exists($key);
  58. }
  59. public static function get($key){
  60. return self::instance()->_redis->get($key);
  61. }
  62. public static function del($key){
  63. $keys = func_get_args();
  64. return self::instance()->_redis->del($keys);
  65. }
  66. public static function expire($key, $expireTime){
  67. return self::instance()->_redis->expire($key, $expireTime);
  68. }
  69. }