PRedis.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /*
  3. * To change this license header, choose License Headers in Project Properties.
  4. * To change this template file, choose Tools | Templates
  5. * and open the template in the editor.
  6. */
  7. require __DIR__.'/Predis/Autoloader.php';
  8. Predis\Autoloader::register();
  9. /**
  10. * Description of Predis
  11. *
  12. * @author jgao
  13. */
  14. class PRedis {
  15. //put your code here
  16. var $redis = null;
  17. public function conn($host, $port, $pwd, $db=0){
  18. $this->redis = new Predis\Client(array(
  19. 'scheme'=>'tcp',
  20. 'host'=>$host,
  21. 'port'=>$port,
  22. 'password'=>$pwd,
  23. ));
  24. $this->redis->select($db);
  25. return $this;
  26. }
  27. public function get($key){
  28. $result = $this->redis->get($key);
  29. if (!$result || $result == "" || $result == null){
  30. return null;
  31. }
  32. return JsonUtil::decode($result);
  33. }
  34. public function getMulti($keys) {
  35. $ctx = $this->redis->mget($keys);
  36. $count = count($ctx);
  37. for($i = 0; $i < $count; $i++) {
  38. $ctx[$i] = JsonUtil::decode($ctx[$i]);
  39. }
  40. return $ctx;
  41. }
  42. public function set($key, $val) {
  43. if($val == null || $val == ""){
  44. return false;
  45. }
  46. $ret = $this->redis->set($key, JsonUtil::encode($val));
  47. return "OK" == $ret;
  48. }
  49. public function cas($key, $value){
  50. return $this->set($key, $value);
  51. }
  52. public function delete($key) {
  53. $infos = array(); $infos[] = $key;
  54. return $this->redis->del($infos) == 1;
  55. }
  56. public function increment($key) {
  57. return $this->redis->incr($key);
  58. }
  59. public function copy($surKey, $desKey) {
  60. return $this->set($desKey, $this->get($surKey));
  61. }
  62. public function close() {
  63. $this->redis->quit();
  64. }
  65. /**
  66. * 获得Redis扩展客户端
  67. * @return Predis\Client
  68. */
  69. public function getRedisClient(){
  70. return $this->redis;
  71. }
  72. /**
  73. * 错误中断
  74. * @param type $msg
  75. */
  76. function halt($msg=null){
  77. exit($msg.'<br /> '.$this->redis->getLastError());
  78. }
  79. }