Rediscache.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. <?php
  2. /**
  3. * This is a Redis exntend class
  4. */
  5. class Rediscache
  6. {
  7. public static $instance = NULL;
  8. public static $linkHandle = array();
  9. var $redis;
  10. //construct:connect redis
  11. public function __construct($host,$port,$auth)
  12. {
  13. $this->initRedis($host,$port,$auth);
  14. }
  15. /**
  16. * Get a instance of MyRedisClient
  17. *
  18. * @param string $key
  19. * @return object
  20. */
  21. static function getInstance($configs)
  22. {
  23. if (!self::$instance) {
  24. self::$instance = new self($configs);
  25. }
  26. return self::$instance;
  27. }
  28. /**
  29. * 初始化Redis
  30. * $host,$port,$auth
  31. */
  32. private function initRedis($host,$port,$auth=''){
  33. $obj = new Redis();
  34. $db = intval($GLOBALS['distribution_cfg']['REDIS_PREFIX_DB']);
  35. if(IS_LONG_LINK){
  36. $connect = $obj->pconnect($host,$port);
  37. if($connect){
  38. if($auth){
  39. $obj->auth($auth);
  40. }
  41. $this->redis = $obj;
  42. }else{
  43. exit("redis connect fail:".$connect);
  44. }
  45. }else{
  46. $connect = $obj->connect($host,$port);
  47. if($connect){
  48. if($auth){
  49. $obj->auth($auth);
  50. }
  51. $this->redis = $obj;
  52. }else{
  53. exit("redis connect fail:".$connect);
  54. }
  55. }
  56. if($db>0){
  57. $this->redis->select($db);
  58. }
  59. }
  60. /**
  61. * 获得redis Resources
  62. *
  63. * @param $key redis存的key/或随机值
  64. * @param string $tag master/slave
  65. */
  66. public function getRedis(){
  67. return $this->redis;
  68. }
  69. /**
  70. * 关闭连接
  71. * pconnect 连接是无法关闭的
  72. *
  73. *
  74. * @return boolean
  75. */
  76. public function close(){
  77. $this->redis->close();
  78. return true;
  79. }
  80. /**
  81. * redis 字符串(String) 类型
  82. * 将key和value对应。如果key已经存在了,它会被覆盖,而不管它是什么类型。
  83. * @param $key
  84. * @param $value
  85. * @param $exp 过期时间
  86. */
  87. public function set($key,$value,$exp=0){
  88. $redis = $this->redis;
  89. $redis->set($key,$value);
  90. !empty($exp) && $redis->expire($key,$exp);
  91. }
  92. public function set_lock($key,$value,$exp=10){
  93. return $this->redis->set($key,$value,array('nx', 'ex' => $exp));
  94. }
  95. /**
  96. * redis 字符串(String) 类型
  97. * 返回key的value。如果key不存在,返回特殊值nil。如果key的value不是string,就返回错误,因为GET只处理string类型的values。
  98. * @param $key
  99. */
  100. public function get($key){
  101. return $this->redis->get($key);
  102. }
  103. /**
  104. * redis 字符串(String) 类型
  105. * KEYS pattern
  106. * 查找所有匹配给定的模式的键
  107. * @param $is_key 默认是一个非正则表达试,使用模糊查询
  108. * @param $key
  109. */
  110. public function keys($key,$is_key=true){
  111. if ($is_key) {
  112. return $this->redis->keys("*$key*");
  113. }
  114. return $this->redis->keys("$key");
  115. }
  116. public function keys_searche($prefix,$search_name){
  117. return $this->redis->keys("$prefix*$search_name*");
  118. }
  119. /**
  120. * 删除一个或多个key
  121. * @param $keys
  122. */
  123. public function delete($keys){
  124. // if(is_array($keys)){
  125. // foreach ($keys as $key){
  126. //
  127. // $this->redis->del($key);
  128. // }
  129. // }else {
  130. //
  131. // $this->redis->del($keys);
  132. // }
  133. $this->redis->delete($keys);
  134. }
  135. /**
  136. * redis 哈希表(hash)类型
  137. * 返回哈希表 $key 中,所有的域和值。
  138. * @param $key
  139. *
  140. */
  141. public function hGetAll($key){
  142. return $this->redis->hGetAll($key);
  143. }
  144. /**
  145. * redis 哈希表(hash)类型
  146. * 批量填充HASH表。不是字符串类型的VALUE,自动转换成字符串类型。使用标准的值。NULL值将被储存为一个空的字符串。
  147. *
  148. * 可以批量添加更新 value,key 不存在将创建,存在则更新值
  149. *
  150. * @param $key
  151. * @param $fieldArr
  152. * @return
  153. * 如果命令执行成功,返回OK。
  154. * 当key不是哈希表(hash)类型时,返回一个错误。
  155. */
  156. public function hMSet($key,$fieldArr){
  157. return $this->redis->hmset($key,$fieldArr);
  158. }
  159. /**
  160. * Gets a value from the hash stored at key.
  161. * If the hash table doesn't exist, or the key doesn't exist, FALSE is returned.
  162. *
  163. * @param string $key
  164. * @param string $hashKey
  165. * @return string The value, if the command executed successfully BOOL FALSE in case of failure
  166. * @link http://redis.io/commands/hget
  167. */
  168. public function hGet($key, $hashKey) {
  169. return $this->redis->hGet($key,$hashKey);
  170. }
  171. /**
  172. * Adds a value to the hash stored at key. If this value is already in the hash, FALSE is returned.
  173. *
  174. * @param string $key
  175. * @param string $hashKey
  176. * @param string $value
  177. * @return int
  178. * 1 if value didn't exist and was added successfully,
  179. * 0 if the value was already present and was replaced, FALSE if there was an error.
  180. * @link http://redis.io/commands/hset
  181. * @example
  182. * <pre>
  183. * $redis->delete('h')
  184. * $redis->hSet('h', 'key1', 'hello'); // 1, 'key1' => 'hello' in the hash at "h"
  185. * $redis->hGet('h', 'key1'); // returns "hello"
  186. *
  187. * $redis->hSet('h', 'key1', 'plop'); // 0, value was replaced.
  188. * $redis->hGet('h', 'key1'); // returns "plop"
  189. * </pre>
  190. */
  191. public function hSet( $key, $hashKey, $value ) {
  192. return $this->redis->hSet($key, $hashKey, $value);
  193. }
  194. public function hMGet( $key, $hashKeys ) {
  195. return $this->redis->hMGet($key,$hashKeys);
  196. }
  197. public function hIncrBy( $key, $hashKey, $value){
  198. return $this->redis->hIncrBy( $key, $hashKey, $value);
  199. }
  200. /**
  201. * redis 哈希表(hash)类型
  202. * 向已存在于redis里的Hash 添加多个新的字段及值
  203. *
  204. * @param $key redis 已存在的key
  205. * @param $field_arr kv形数组
  206. */
  207. public function hAddFieldArr($key,$field_arr){
  208. foreach ($field_arr as $k=>$v){
  209. $this->hAddFieldOne($key, $k, $v);
  210. }
  211. }
  212. /**
  213. * 向已存在于redis里的Hash 添加一个新的字段及值
  214. * @param $key
  215. * @param $field_name
  216. * @param $field_value
  217. * @return bool
  218. */
  219. public function hAddFieldOne($key,$field_name,$field_value){
  220. return $this->redis->hsetnx($key,$field_name,$field_value);
  221. }
  222. /**
  223. * 向Hash里添加多个新的字段或修改一个已存在字段的值
  224. * @param $key
  225. * @param $field_arr
  226. */
  227. public function hAddOrUpValueArr($key,$field_arr){
  228. foreach ($field_arr as $k=>$v){
  229. $this->hAddOrUpValueOne($key, $k, $v);
  230. }
  231. }
  232. /**
  233. * 向Hash里添加多个新的字段或修改一个已存在字段的值
  234. * @param $key
  235. * @param $field_name
  236. * @param $field_value
  237. * @return boolean
  238. * 1 if value didn't exist and was added successfully,
  239. * 0 if the value was already present and was replaced, FALSE if there was an error.
  240. */
  241. public function hAddOrUpValueOne($key,$field_name,$field_value){
  242. return $this->redis->hset($key,$field_name,$field_value);
  243. }
  244. /**
  245. * 删除哈希表key中的多个指定域,不存在的域将被忽略。
  246. * @param $key
  247. * @param $field_arr
  248. */
  249. public function hDel($key,$field_arr){
  250. // foreach ($field_arr as $var){
  251. // $this->hDelOne($key,$var);
  252. // }
  253. $keys = array();
  254. if(is_array($field_arr)){
  255. array_unshift($field_arr,$key);
  256. $keys = $field_arr;
  257. }else{
  258. $keys = array($key,$field_arr);
  259. }
  260. return call_user_func_array(array($this->redis, "hDel"),$keys);
  261. }
  262. /**
  263. * 删除哈希表key中的一个指定域,不存在的域将被忽略。
  264. *
  265. * @param $key
  266. * @param $field
  267. * @return BOOL TRUE in case of success, FALSE in case of failure
  268. */
  269. public function hDelOne($key,$field){
  270. return $this->redis->hdel($key,$field);
  271. }
  272. /**
  273. * 重命名key
  274. *
  275. * @param $oldkey
  276. * @param $newkey
  277. */
  278. public function renameKey($oldkey,$newkey){
  279. return $this->redis->rename($oldkey,$newkey);
  280. }
  281. /**
  282. * 删除一个或多个key
  283. * @param $keys
  284. */
  285. // public function delKey($keys){
  286. // if(is_array($keys)){
  287. // foreach ($keys as $key){
  288. // $this->redis->del($key);
  289. // }
  290. // }else {
  291. // $this->redis->del($keys);
  292. // }
  293. // }
  294. /**
  295. * 添加一个字符串值到LIST容器的顶部(左侧),如果KEY不存在,曾创建一个LIST容器,如果KEY存在并且不是一个LIST容器,那么返回FLASE。
  296. *
  297. * @param unknown $key
  298. * @param unknown $val
  299. */
  300. public function lPush($key,$val){
  301. return $this->redis->lPush($key,$val);
  302. }
  303. public function rPush($key,$field_arr){
  304. // $keys =array($key,$vals);
  305. if(is_array($field_arr)){
  306. array_unshift($field_arr,$key);
  307. $keys = $field_arr;
  308. }else{
  309. $keys = array($key,$field_arr);
  310. }
  311. // return $this->redis->rPush($key,$val);
  312. return call_user_func_array(array($this->redis, "rPush"), $keys);
  313. }
  314. /**
  315. * 返回LIST顶部(左侧)的VALUE,并且从LIST中把该VALUE弹出。
  316. * @param unknown $key
  317. */
  318. public function lPop($key){
  319. return $this->redis->lPop($key);
  320. }
  321. public function lGetRange($key,$start,$end){
  322. return $this->redis->lGetRange($key,$start,$end);
  323. }
  324. public function lRange($key,$start,$end){
  325. return $this->redis->lRange($key,$start,$end);
  326. }
  327. /**
  328. * 批量的添加多个key 到redis
  329. * @param $fieldArr
  330. */
  331. // public function mSetnx($fieldArr){
  332. //
  333. // $this->redis->mSetnx($fieldArr);
  334. // }
  335. /*
  336. * 检查给定 key 是否存在。
  337. * 若 key 存在,返回 1 ,否则返回 0 。
  338. */
  339. public function exists($key){
  340. return $this->redis->exists($key);
  341. }
  342. /*
  343. *将 key 中储存的数字值增一。
  344. *如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。
  345. */
  346. public function incr($key){
  347. $this->redis->incr($key);
  348. }
  349. /*
  350. * 取得所有指定键的值。如果一个或多个键不存在,该数组中该键的值为假
  351. * @param $keys
  352. * 返回值:返回包含所有键的值的数组
  353. */
  354. public function getMultiple($keys){
  355. if(is_array($keys)){
  356. $keys_array = array();
  357. foreach($keys as $key){
  358. $keys_array[] = $key;
  359. }
  360. return $this->redis->getMultiple($keys_array);
  361. }else{
  362. return false;
  363. }
  364. }
  365. //====Set 有序集合=====
  366. public function sAdd($key,$value1){
  367. return $this->redis->sAdd($key,$value1);
  368. }
  369. public function srem($key,$value1){
  370. return $this->redis->srem($key,$value1);
  371. }
  372. public function sMembers($key){
  373. return $this->redis->sMembers($key);
  374. }
  375. public function sismember($key,$value){
  376. return $this->redis->sIsMember($key,$value);
  377. }
  378. public function sCard($key){
  379. return $this->redis->sCard($key);
  380. }
  381. //回一个所有指定键的交集。如果只指定一个键,那么这个命令生成这个集合的成员。如果不存在某个键,则返回FALSE。
  382. public function sinter( $keys){
  383. return call_user_func_array(array($this->redis, "sinter"), $keys);
  384. }
  385. //====SortedSet 有序集合=====
  386. /*
  387. * 构建一个集合(有序集合)
  388. * @param string $key 集合名称
  389. * @param string $value1 值
  390. * @param int $score1 值
  391. * return 被成功添加的新成员的数量,不包括那些被更新的、已经存在的成员。
  392. */
  393. public function zAdd($key,$score1,$value1){
  394. return $this->redis->zAdd($key,$score1,$value1);
  395. }
  396. public function zMAdd($key,$data){
  397. $array = array();
  398. $array[] = $key;
  399. foreach($data as $k => $v) {
  400. $array[] = $v;
  401. $array[] = $k;
  402. }
  403. $keys = array_values($array);
  404. return call_user_func_array(array($this->redis, 'zAdd'), $keys);
  405. }
  406. /**
  407. * Returns the score of a given member in the specified sorted set.
  408. *
  409. * @param string $key
  410. * @param string $member
  411. * @return float
  412. * @link http://redis.io/commands/zscore
  413. * @example
  414. * <pre>
  415. * $redis->zAdd('key', 2.5, 'val2');
  416. * $redis->zScore('key', 'val2'); // 2.5
  417. * </pre>
  418. * 查找 key中member的值
  419. */
  420. public function zScore( $key, $member ) {
  421. return $this->redis->zScore( $key, $member );
  422. }
  423. /**
  424. * Returns the cardinality of an ordered set.
  425. *
  426. * @param string $key
  427. * @return int the set's cardinality
  428. * @example
  429. * <pre>
  430. * $redis->zAdd('key', 0, 'val0');
  431. * $redis->zAdd('key', 2, 'val2');
  432. * $redis->zAdd('key', 10, 'val10');
  433. * $redis->zCard('key'); // 3
  434. * </pre>
  435. */
  436. public function zCard($key){
  437. return $this->redis->zCard($key);
  438. }
  439. /**
  440. * Returns the number of elements of the sorted set stored at the specified key which have
  441. * scores in the range [start,end]. Adding a parenthesis before start or end excludes it
  442. * from the range. +inf and -inf are also valid limits.
  443. *
  444. * @param string $key
  445. * @param string $start
  446. * @param string $end
  447. * @return int the size of a corresponding zRangeByScore.
  448. * @link http://redis.io/commands/zcount
  449. * @example
  450. * <pre>
  451. * $redis->zAdd('key', 0, 'val0');
  452. * $redis->zAdd('key', 2, 'val2');
  453. * $redis->zAdd('key', 10, 'val10');
  454. * $redis->zCount('key', 0, 3); // 2, corresponding to array('val0', 'val2')
  455. * </pre>
  456. * score 值在 min 和 max 之间的成员的数量。
  457. */
  458. public function zCount( $key, $start, $end ) {
  459. return $this->redis->zCount($key, $start, $end);
  460. }
  461. /**
  462. * Increments the score of a member from a sorted set by a given amount.
  463. *
  464. * @param string $key
  465. * @param float $value (double) value that will be added to the member's score
  466. * @param string $member
  467. * @return float the new value
  468. * @example
  469. * <pre>
  470. * $redis->delete('key');
  471. * $redis->zIncrBy('key', 2.5, 'member1'); // key or member1 didn't exist, so member1's score is to 0
  472. * // before the increment and now has the value 2.5
  473. * $redis->zIncrBy('key', 1, 'member1'); // 3.5
  474. * </pre>
  475. * member 成员的新 score 值,以字符串形式表示。
  476. */
  477. public function zIncrBy( $key, $value, $member ) {
  478. return $this->redis->zIncrBy( $key, $value, $member );
  479. }
  480. /**
  481. * Returns a range of elements from the ordered set stored at the specified key,
  482. * with values in the range [start, end]. start and stop are interpreted as zero-based indices:
  483. * 0 the first element,
  484. * 1 the second ...
  485. * -1 the last element,
  486. * -2 the penultimate ...
  487. *
  488. * @param string $key
  489. * @param int $start
  490. * @param int $end
  491. * @param bool $withscores
  492. * @return array Array containing the values in specified range.
  493. * @link http://redis.io/commands/zrange
  494. * @example
  495. * <pre>
  496. * $redis->zAdd('key1', 0, 'val0');
  497. * $redis->zAdd('key1', 2, 'val2');
  498. * $redis->zAdd('key1', 10, 'val10');
  499. * $redis->zRange('key1', 0, -1); // array('val0', 'val2', 'val10')
  500. * // with scores
  501. * $redis->zRange('key1', 0, -1, true); // array('val0' => 0, 'val2' => 2, 'val10' => 10)
  502. * </pre>
  503. * 指定区间内,带有 score 值(可选)的有序集成员的列表。
  504. */
  505. public function zRange( $key, $start, $end, $withscores = null ) {
  506. return $this->redis->zRange( $key, $start, $end, $withscores) ;
  507. }
  508. public function zRevRange( $key, $start, $end, $withscores = null ) {
  509. return $this->redis->zRevRange( $key, $start, $end, $withscores) ;
  510. }
  511. /**
  512. * Deletes a specified member from the ordered set.
  513. *
  514. * @param string $key
  515. * @param string $member1
  516. * @param string $member2
  517. * @param string $memberN
  518. * @return int Number of deleted values
  519. * @link http://redis.io/commands/zrem
  520. * @example
  521. * <pre>
  522. * $redis->zAdd('z', 1, 'v2', 2, 'v2', 3, 'v3', 4, 'v4' ); // int(2)
  523. * $redis->zRem('z', 'v2', 'v3'); // int(2)
  524. * var_dump( $redis->zRange('z', 0, -1) );
  525. * //// Output:
  526. * // array(2) {
  527. * // [0]=> string(2) "v1"
  528. * // [1]=> string(2) "v4"
  529. * // }
  530. * </pre>
  531. * 返回值:被成功移除的成员的数量,不包括被忽略的成员。
  532. */
  533. public function zRem( $key, $member1 ) {
  534. return $this->redis->zRem( $key, $member1 );
  535. }
  536. //并集
  537. public function zUnionStore($new_key,$keys,$withscore=true,$AGGREGATE = 'min'){
  538. return $this->redis->zUnionStore($new_key,$keys,$withscore,$AGGREGATE);
  539. }
  540. //交集 保存到 destination 的结果集的基数。
  541. public function zInterStore($new_key,$keys,$withscore = null,$AGGREGATE = 'max'){
  542. return $this->redis->zInterStore($new_key,$keys,$withscore,$AGGREGATE);
  543. }
  544. /**
  545. * Returns the elements of the sorted set stored at the specified key which have scores in the
  546. * range [start,end]. Adding a parenthesis before start or end excludes it from the range.
  547. * +inf and -inf are also valid limits.
  548. *
  549. * zRevRangeByScore returns the same items in reverse order, when the start and end parameters are swapped.
  550. *
  551. * @param string $key
  552. * @param int $start
  553. * @param int $end
  554. * @param array $options Two options are available:
  555. * - withscores => TRUE,
  556. * - and limit => array($offset, $count)
  557. * @return array Array containing the values in specified range.
  558. * @link http://redis.io/commands/zrangebyscore
  559. * @example
  560. * <pre>
  561. * $redis->zAdd('key', 0, 'val0');
  562. * $redis->zAdd('key', 2, 'val2');
  563. * $redis->zAdd('key', 10, 'val10');
  564. * $redis->zRangeByScore('key', 0, 3); // array('val0', 'val2')
  565. * $redis->zRangeByScore('key', 0, 3, array('withscores' => TRUE); // array('val0' => 0, 'val2' => 2)
  566. * $redis->zRangeByScore('key', 0, 3, array('limit' => array(1, 1)); // array('val2' => 2)
  567. * $redis->zRangeByScore('key', 0, 3, array('limit' => array(1, 1)); // array('val2')
  568. * $redis->zRangeByScore('key', 0, 3, array('withscores' => TRUE, 'limit' => array(1, 1)); // array('val2' => 2)
  569. * </pre>
  570. */
  571. public function zRangeByScore( $key, $start, $end, $options = array() ) {
  572. return $this->redis->zRangeByScore($key, $start, $end,$options);
  573. }
  574. public function srandmember($key,$num){
  575. return $this->redis->srandmember($key,$num);
  576. }
  577. public function multi($mode=Redis::MULTI) {
  578. if(IS_REDIS_WORK) {
  579. return $this->redis->multi($mode);
  580. }else{
  581. return $this->redis;
  582. }
  583. }
  584. public function exec( ) {
  585. if(IS_REDIS_WORK){
  586. $this->redis->exec();
  587. }else{
  588. return false;
  589. }
  590. }
  591. public function discard( ) {
  592. $this->redis->discard();
  593. }
  594. public function watch($key ) {
  595. $this->redis->watch($key);
  596. }
  597. }
  598. ?>