RedisInstance.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. <?php
  2. /**
  3. * redis https://phpredis.github.io/phpredis/Redis.html
  4. * 兼容yii cache接口,可以使用\Yii::app()->cache->get() 形式使用
  5. * 也可以使用: Redis::getInstance()->get() 形式使用
  6. * 推荐使用Redis::getInstance()形式,\Yii::app()->cache只是为了兼容YII框架处理,redis接口远比yii框架的cache接口丰富。
  7. */
  8. class RedisInstance extends \CCache
  9. {
  10. /**
  11. * 无穷大
  12. * @var string
  13. */
  14. const MAX_VALUE = '+inf';
  15. /**
  16. * 无穷小
  17. * @var string
  18. */
  19. const MIN_VALUE = '-inf';
  20. /**
  21. * 聚合类型,求和
  22. * @var string
  23. */
  24. const AGGREGATE_TYPE_SUM = 'SUM';
  25. /**
  26. * 聚合类型,最大值
  27. * @var string
  28. */
  29. const AGGREGATE_TYPE_MAX = 'MAX';
  30. /**
  31. * 聚合类型,最小值
  32. * @var string
  33. */
  34. const AGGREGATE_TYPE_MIN = 'MIN';
  35. /**
  36. * redis
  37. * @var Redis
  38. */
  39. private static $_instance = null;
  40. /**
  41. * redis链接
  42. * @var \Redis
  43. */
  44. private $_redis = null;
  45. private $_conf = array();
  46. private function __construct()
  47. {
  48. $this->_conf = \Yii::app()->params['redis'];
  49. if (empty($this->_conf) || empty($this->_conf['host']) || empty($this->_conf['port'])) {
  50. throw new Exception("redis config invalid.");
  51. }
  52. try{
  53. if (!$this->_connect()) {
  54. Logger::error("connect to redis failure.");
  55. throw new Exception("connect to redis failure");
  56. }
  57. } catch (\RedisException $e) {
  58. Logger::error("connect to redis failure. msg=" . $e->getMessage());
  59. throw new Exception("connect to redis failure, msg=" . $e->getMessage());
  60. }
  61. }
  62. /**
  63. * 获取redis实例
  64. * @return RedisInstance
  65. */
  66. public static function getInstance()
  67. {
  68. if (null === self::$_instance) {
  69. $start = microtime(true);
  70. self::$_instance = new RedisInstance();
  71. if (($spend = microtime(true) - $start) > 3) {
  72. Logger::info('redis_connect_timeout ' . $spend);
  73. }
  74. }
  75. return self::$_instance;
  76. }
  77. /**
  78. * 返回redis原始实例
  79. * @return \Redis
  80. */
  81. public function getOriginInstance()
  82. {
  83. return $this->_redis;
  84. }
  85. /**
  86. * Get the value related to the specified key
  87. * @param string $key
  88. * @return String or Bool: If key didn't exist, FALSE is returned. Otherwise, the value related to this key is returned.
  89. */
  90. public function get($key)
  91. {
  92. return $this->_redis->get($key);
  93. }
  94. /**
  95. * Get the values of all the specified keys. If one or more keys dont exist, the array will contain FALSE at the position of the key.
  96. * @param array $keys - key数组
  97. * @return Array: Array containing the values related to keys in argument
  98. */
  99. public function mget($keys)
  100. {
  101. return $this->_redis->mget($keys);
  102. }
  103. /**
  104. * Set the string value in argument as value of the key
  105. * @param string $key
  106. * @param mixed $value - 任意值
  107. * @param int $expire - 过期时间,单位秒
  108. * @return bool 成功返回true
  109. */
  110. public function set($key, $value, $expire = 0, $dependency = null)
  111. {
  112. if ($expire > 0) {
  113. return $this->_redis->set($key, $value, $expire);
  114. }
  115. return $this->_redis->set($key, $value);
  116. }
  117. /**
  118. * 设置key值,如果key存在则失败
  119. * @param string $key
  120. * @param mixed $value - 任意值
  121. * @param int $expire - 过期时间,单位秒
  122. * @return bool 成功返回true, key存在返回false
  123. */
  124. public function setNx($key, $value, $expire = 0)
  125. {
  126. return $this->_redis->set($key, $value, ['nx', 'ex' => $expire]);
  127. }
  128. /**
  129. * Verify if the specified key exists.
  130. * @param string $key
  131. * @return BOOL: If the key exists, return TRUE, otherwise return FALSE.
  132. */
  133. public function exists($key)
  134. {
  135. return $this->_redis->exists($key);
  136. }
  137. /**
  138. * Sets a value and returns the previous entry at that key.
  139. * @param string $key
  140. * @param mixed $value - 任意值
  141. * @param int $expire - 过期时间,单位秒
  142. */
  143. public function getSet($key, $value, $expire = 0)
  144. {
  145. $prev = $this->_redis->getSet($key, $value);
  146. if ($expire > 0) {
  147. $this->_redis->expire($key, $expire);
  148. }
  149. return $prev;
  150. }
  151. /**
  152. * 增加key 的值
  153. * @param string $key
  154. * @param number $step - 增加步长,每次加多少
  155. * @param int $expire - 超时时间
  156. * @return int 最新值
  157. */
  158. public function incr($key, $step = 1, $expire = 0)
  159. {
  160. $ret = false;
  161. if ($step > 1) {
  162. $ret = $this->_redis->incrBy($key, $step);
  163. }
  164. else {
  165. $ret = $this->_redis->incr($key);
  166. }
  167. if (false !== $ret && $expire > 0) {
  168. $this->_redis->expire($key, $expire);
  169. }
  170. return $ret;
  171. }
  172. /**
  173. * 减少key 的值
  174. * @param string $key
  175. * @param number $step - 减少步长,每次减多少
  176. * @param int $expire - 超时时间
  177. * @return int 最新值
  178. */
  179. public function decr($key, $step = 1, $expire = 0)
  180. {
  181. $ret = false;
  182. if ($step > 1) {
  183. $ret = $this->_redis->decrBy($key, $step);
  184. }
  185. else {
  186. $ret = $this->_redis->decr($key);
  187. }
  188. if (false !== $ret && $expire > 0) {
  189. $this->_redis->expire($key, $expire);
  190. }
  191. return $ret;
  192. }
  193. /**
  194. * Remove specified keys.
  195. * @param string $key - 批量删除,传递key数组
  196. * @return mixed - Long Number of keys deleted.
  197. */
  198. public function delete($key)
  199. {
  200. return $this->_redis->del($key);
  201. }
  202. /**
  203. * 重命名key
  204. * @param $srcKey - 原key
  205. * @param $dstKey - 改名后的key
  206. * @return bool - 成功返回true
  207. */
  208. public function rename($srcKey, $dstKey)
  209. {
  210. return $this->_redis->rename($srcKey, $dstKey);
  211. }
  212. /**
  213. * 设置key超时时间,单位秒
  214. * @param string $key - 设置key超时时间
  215. * @param int $expire - 不限制设置-1
  216. * @return bool 成功返回true
  217. */
  218. public function expire($key, $expire)
  219. {
  220. return $this->_redis->expire($key, $expire);
  221. }
  222. /**
  223. * 获取该key在redis里的剩余存活时间,单位秒
  224. * @param string $key -key
  225. * @return int|false -成功返回时间
  226. */
  227. public function ttl($key)
  228. {
  229. $restTime=$this->_redis->ttl($key);
  230. if($restTime>=0)
  231. {
  232. return $restTime;
  233. }
  234. else
  235. {
  236. return false;
  237. }
  238. }
  239. /**
  240. * hash表操作 - 删除hash字段
  241. * @param string $key
  242. * @param string $field - hash字段
  243. * @return LONG the number of deleted keys, 0 if the key doesn't exist, FALSE if the key isn't a hash.
  244. */
  245. public function hDel($key, $field)
  246. {
  247. return $this->_redis->hDel($key, $field);
  248. }
  249. /**
  250. * hash表操作 - 检测hash 字段是否存在
  251. * @param string $key
  252. * @param string $field - hash字段
  253. * @return BOOL: If the member exists in the hash table, return TRUE, otherwise return FALSE.
  254. */
  255. public function hExists($key, $field)
  256. {
  257. return $this->_redis->hExists($key, $field);
  258. }
  259. /**
  260. * hash表操作 - 获取hash字段的值
  261. * @param string $key
  262. * @param string $field - 字段
  263. * @return mixed | false - 成功返回值,失败返回false
  264. */
  265. public function hGet($key, $field)
  266. {
  267. return $this->_redis->hGet($key, $field);
  268. }
  269. /**
  270. * hash表操作 - 获取hash表中所有字段值
  271. * @param string $key
  272. * @return array
  273. */
  274. public function hGetAll($key)
  275. {
  276. return $this->_redis->hGetAll($key);
  277. }
  278. /**
  279. * hash表操作 - 增加hash字段的数值
  280. * @param string $key
  281. * @param string $field - hash字段
  282. * @param number $step - 增加步长,每次加多少
  283. * @param int $expire - 超时时间
  284. * @return LONG 返回新值
  285. */
  286. public function hIncrBy($key, $field, $step = 1, $expire = 0)
  287. {
  288. $ret = $this->_redis->hIncrBy($key, $field, $step);
  289. if (false !== $ret && $expire > 0) {
  290. $this->_redis->expire($key, $expire);
  291. }
  292. return $ret;
  293. }
  294. /**
  295. * hash表操作 - 返回全部hash字段
  296. * @param string $key
  297. * @return array
  298. */
  299. public function hKeys($key)
  300. {
  301. return $this->_redis->hKeys($key);
  302. }
  303. /**
  304. * hash表操作 - 返回hash的字段数
  305. * @param string $key
  306. * @return int key不存在返回false
  307. */
  308. public function hLen($key)
  309. {
  310. return $this->_redis->hLen($key);
  311. }
  312. /**
  313. * hash表操作 - 批量获取hash的字段值
  314. * @param string $key
  315. * @param array $fields - hash字段
  316. * @return boolean|mixed
  317. */
  318. public function hMGet($key, array $fields)
  319. {
  320. if (empty($fields)) {
  321. return false;
  322. }
  323. return $this->_redis->hMget($key, $fields);
  324. }
  325. /**
  326. * hash表操作 - 批量设置hash字段值
  327. * @param string $key
  328. * @param array $fields - hash字段数组, 例:array('uid' => 1, 'name' => 'lewaimai')
  329. * @param int $expire - 过期时间,单位秒
  330. * @return bool 成功返回true
  331. */
  332. public function hMSet($key, array $fields, $expire = 0)
  333. {
  334. if (empty($fields)) {
  335. return false;
  336. }
  337. $ret = $this->_redis->hMset($key, $fields);
  338. if (false !== $ret && $expire > 0) {
  339. $this->_redis->expire($key, $expire);
  340. }
  341. return $ret;
  342. }
  343. /**
  344. * hash表操作 - 设置hash字段值
  345. * @param string $key
  346. * @param string $field - hash字段
  347. * @param mixed $value - 任意值
  348. * @param int $expire - 过期时间,单位秒
  349. * @return bool 成功返回true
  350. */
  351. public function hSet($key, $field, $value, $expire = 0)
  352. {
  353. $ret = $this->_redis->hSet($key, $field, $value);
  354. if (false !== $ret && $expire > 0) {
  355. $this->_redis->expire($key, $expire);
  356. }
  357. return $ret;
  358. }
  359. /**
  360. * hash表操作 - 设置hash字段值, 如果字段存在则失败。
  361. * @param string $key
  362. * @param string $field - hash字段
  363. * @param mixed $value - 任意值
  364. * @param int $expire - 过期时间,单位秒
  365. * @return bool 成功返回true, hash字段已经存在
  366. */
  367. public function hSetNx($key, $field, $value, $expire = 0)
  368. {
  369. $ret = $this->_redis->hSetNx($key, $field, $value);
  370. if (true === $ret && $expire > 0) {
  371. $this->_redis->expire($key, $expire);
  372. }
  373. return $ret;
  374. }
  375. /**
  376. * list操作 - 获取指定位置的元素
  377. * @param string $key
  378. * @param int $index - 索引位置从0开始, -1代表最后一个
  379. * @return mixed | false -成功返回结果,失败返回false
  380. */
  381. public function lGet($key, $index)
  382. {
  383. return $this->_redis->lindex($key, $index);
  384. }
  385. /**
  386. * list操作 - 在指定元素之前或之后插入元素
  387. * @param string $key
  388. * @param mixed $pivot - 参考元素,在该元素之前或者之后插入, 如果该元素不存在,则放弃插入
  389. * @param mixed $value - 待插入元素
  390. * @param int $posType - 插入类型,\Redis::BEFORE 或则 \Redis::AFTER
  391. * @return int 成功返回list元素个数,失败返回-1表示$pivot不存在。
  392. */
  393. public function lInsert($key, $pivot, $value, $posType = \Redis::AFTER)
  394. {
  395. return $this->_redis->lInsert($key, $posType, $pivot, $value);
  396. }
  397. /**
  398. * list操作 - 根据范围 [$start, $end] 获取元素
  399. * 例如:获取全部数据的范围条件 [0, -1]
  400. * @param string $key
  401. * @param int $start - 开始位置
  402. * @param int $end - 结束位置
  403. * @return array
  404. */
  405. public function lRange($key, $start, $end)
  406. {
  407. return $this->_redis->lRange($key, $start, $end);
  408. }
  409. /**
  410. * list操作 - 返回list元素个数
  411. * @param string $key
  412. * @return int | false 成功返回元素个数,失败返回false
  413. */
  414. public function lSize($key)
  415. {
  416. return $this->_redis->lLen($key);
  417. }
  418. /**
  419. * list操作 - 从head弹出一个元素
  420. * @param string $key
  421. * @return mixed | false 成功返回元素,失败或则为空返回false
  422. */
  423. public function lPop($key)
  424. {
  425. return $this->_redis->lPop($key);
  426. }
  427. /**
  428. * list操作 - 从head插入一个元素, list不存在则创建
  429. * @param string $key
  430. * @param mixed $value - 元素
  431. * @param int $expire - 超时时间,0不限制
  432. * @return int | false 成功返回list元素个数
  433. */
  434. public function lPush($key, $value, $expire = 0)
  435. {
  436. $ret = $this->_redis->lPush($key, $value);
  437. if (false !== $ret && $expire > 0) {
  438. $this->_redis->expire($key, $expire);
  439. }
  440. return $ret;
  441. }
  442. /**
  443. * list操作 - 从head插入一个元素, list不存在则放弃写入
  444. * @param string $key
  445. * @param mixed $value - 元素
  446. * @param int $expire - 超时时间,0不限制
  447. * @return int | false 成功返回list元素个数
  448. */
  449. public function lPushx($key, $value)
  450. {
  451. return $this->_redis->lPushx($key, $value);
  452. }
  453. /**
  454. * list操作 - 从list中删除前面$count个$value元素
  455. * @param string $key
  456. * @param string $value - 待删除元素, 从head开始查找
  457. * @param int $count - 需要删除几个元素, 0则全部删除
  458. * @return int | false 成功返回删除元素个数
  459. */
  460. public function lRem($key, $value, $count)
  461. {
  462. return $this->_redis->lRem($key, $value, $count);
  463. }
  464. /**
  465. * list操作 - 设置list指定位置的值
  466. * @param string $key
  467. * @param int $index - 索引,从0开始
  468. * @param mixed $value
  469. * @param int $expire - 超时时间,0不限制
  470. * @return bool 成功返回true
  471. */
  472. public function lSet($key, $index, $value, $expire = 0)
  473. {
  474. $ret = $this->_redis->lSet($key, $index, $value);
  475. if (false !== $ret && $expire > 0) {
  476. $this->_redis->expire($key, $expire);
  477. }
  478. return $ret;
  479. }
  480. /**
  481. * list操作 - 根据范围缩小list数据
  482. * @param string $key
  483. * @param int $start - 开始索引
  484. * @param int $stop - 结束索引
  485. * @return bool 成功返回true
  486. */
  487. public function lTrim($key, $start, $stop)
  488. {
  489. return $this->_redis->lTrim($key, $start, $stop);
  490. }
  491. /**
  492. * list操作 - 从表尾弹出元素
  493. * @param string $key
  494. * @return mixed | false 成功返回元素,失败或则为空返回false
  495. */
  496. public function rPop($key)
  497. {
  498. return $this->_redis->rPop($key);
  499. }
  500. /**
  501. * list操作 - 从表尾插入一个元素, list不存在则创建
  502. * @param string $key
  503. * @param mixed $value - 元素
  504. * @param int $expire - 超时时间,0不限制
  505. * @return int | false 成功返回list元素个数
  506. */
  507. public function rPush($key, $value, $expire = 0)
  508. {
  509. $ret = $this->_redis->rPush($key, $value);
  510. if (false !== $ret && $expire > 0) {
  511. $this->_redis->expire($key, $expire);
  512. }
  513. return $ret;
  514. }
  515. /**
  516. * list操作 - 从表尾插入一个元素, list不存在则放弃写入
  517. * @param string $key
  518. * @param mixed $value - 元素
  519. * @return int | false 成功返回list元素个数
  520. */
  521. public function rPushX($key, $value)
  522. {
  523. return $this->_redis->rPushX($key, $value);
  524. }
  525. /**
  526. * 集合操作 - 添加元素, 如果元素已经存在返回false
  527. * @param string $key
  528. * @param string $value - 允许批量写入,传入数组即可,批量写入,只要有一个元素插入失败则返回false
  529. * @param int $expire - 超时时间, 0不限制
  530. * @return int | false 成功返回集合元素个数,失败返回false
  531. */
  532. public function sAdd($key, $value, $expire = 0)
  533. {
  534. $ret = false;
  535. if (!empty($value) && is_array($value)) {
  536. $params = [$key];
  537. $params = array_merge($params, $value);
  538. $ret = call_user_func_array(array($this->_redis, 'sAdd'), $params);
  539. } else {
  540. $ret = $this->_redis->sAdd($key, $value);
  541. }
  542. if ($ret && $expire > 0) {
  543. $this->_redis->expire($key, $expire);
  544. }
  545. return $ret ? true : false;
  546. }
  547. /**
  548. * 集合操作 - 返回所有集合元素
  549. * @param string $key
  550. * @return array
  551. */
  552. public function sMembers($key)
  553. {
  554. return $this->_redis->sMembers($key);
  555. }
  556. /**
  557. * 集合操作 - 检测集合是否包含指定元素
  558. * @param string $key
  559. * @param mixed $value
  560. * @return bool 存在返回true
  561. */
  562. public function sIsMember($key, $value)
  563. {
  564. return $this->_redis->sIsMember($key, $value);
  565. }
  566. /**
  567. * 集合操作 - 返回集合元素个数, key不存在返回0
  568. * @param string $key
  569. * @return int
  570. */
  571. public function sSize($key)
  572. {
  573. return $this->_redis->scard($key);
  574. }
  575. /**
  576. * 集合操作 - 将一个元素从一个集合移动到另外一个集合
  577. * @param string $srcKey - 源集合
  578. * @param string $dstKey - 目标集合
  579. * @param mixed $member - 待移动元素
  580. * @return bool 成功返回true
  581. */
  582. public function sMove($srcKey, $dstKey, $member)
  583. {
  584. return $this->_redis->sMove($srcKey, $dstKey, $member);
  585. }
  586. /**
  587. * 集合操作 - 随机弹出一个集合元素
  588. * @param string $key
  589. * @return mixed | false - 成功返回集合元素,失败返回false
  590. */
  591. public function sPop($key)
  592. {
  593. return $this->_redis->sPop($key);
  594. }
  595. /**
  596. * 集合操作 - 随机获取一个元素,不删除该元素
  597. * @param string $key
  598. * @param int $count - 随机返回多少个元素
  599. * @return mixed |false - 如果$count=1则返回一个元素,$count > 1则返回一个元素数组
  600. */
  601. public function sRandMember($key, $count = 1)
  602. {
  603. $ret = false;
  604. if ($count > 1) {
  605. $ret = $this->_redis->sRandMember($key, $count);
  606. //bug处理,srandmember没有反序列化数据
  607. if (!empty($ret)) {
  608. foreach ($ret as $k => $v) {
  609. $ret[$k] = unserialize($v);
  610. }
  611. }
  612. }
  613. else {
  614. $ret = unserialize($this->_redis->sRandMember($key));
  615. }
  616. return $ret;
  617. }
  618. /**
  619. * 集合操作 - 计算key1的差集, 允许传递N个参数,最少传递2个参数
  620. * @param string $key1
  621. * @param string $key2
  622. * @return boolean|array 成功返回array, 失败返回false
  623. */
  624. public function sDiff($key1, $key2)
  625. {
  626. if (func_num_args() < 2) {
  627. return false;
  628. }
  629. return call_user_func_array([$this->_redis, "sDiff"], func_get_args());
  630. }
  631. /**
  632. * 集合操作 - 计算key1的差集, 允许传递N个参数,最少传递3个参数, 结果保存在$dstKey
  633. * @param string $dstKey - 结果保存在该key
  634. * @param string $key1
  635. * @param string $key2
  636. * @return boolean|int 成功返回$dstKey集合元素个数, 失败返回false
  637. */
  638. public function sDiffStore($dstKey, $key1, $key2)
  639. {
  640. if (func_num_args() < 3) {
  641. return false;
  642. }
  643. return call_user_func_array([$this->_redis, "sDiffStore"], func_get_args());
  644. }
  645. /**
  646. * 集合操作 - 计算交集, 允许传递N个参数,最少传递2个参数,只要参与交集运算其中的一个集合key不存在,则返回false
  647. * @param string $key1
  648. * @param string $key2
  649. * @return boolean|array 成功返回array, 失败返回false
  650. */
  651. public function sInter($key1, $key2)
  652. {
  653. if (func_num_args() < 2) {
  654. return false;
  655. }
  656. return call_user_func_array([$this->_redis, "sInter"], func_get_args());
  657. }
  658. /**
  659. * 集合操作 - 计算交集, 允许传递N个参数,最少传递3个参数,只要参与交集运算其中的一个集合key不存在,则返回false
  660. * @param string $dstKey - 结果保存在该key
  661. * @param string $key1
  662. * @param string $key2
  663. * @return boolean|int 成功返回$dstKey集合元素个数, 失败返回false
  664. */
  665. public function sInterStore($dstKey, $key1, $key2)
  666. {
  667. if (func_num_args() < 3) {
  668. return false;
  669. }
  670. return call_user_func_array([$this->_redis, "sInterStore"], func_get_args());
  671. }
  672. /**
  673. * 集合操作 - 删除集合元素
  674. * @param string $key
  675. * @param mixed $member - 集合元素, 支持批量删除,传递数组即可
  676. * @return int 返回删除元素个数
  677. */
  678. public function sRem($key, $member)
  679. {
  680. if (!empty($member) && is_array($member)) {
  681. $params = [$key];
  682. $params = array_merge($params, $member);
  683. return call_user_func_array([$this->_redis, 'sRem'], $params);
  684. }
  685. return $this->_redis->sRem($key, $member);
  686. }
  687. /**
  688. * 集合操作 - 计算并集, 允许传递N个参数,最少传递2个参数
  689. * @param string $key1
  690. * @param string $key2
  691. * @return boolean|array 成功返回array, 失败返回false
  692. */
  693. public function sUnion($key1, $key2)
  694. {
  695. if (func_num_args() < 2) {
  696. return false;
  697. }
  698. return call_user_func_array([$this->_redis, "sUnion"], func_get_args());
  699. }
  700. /**
  701. * 集合操作 - 计算并集, 允许传递N个参数,最少传递3个参数
  702. * @param string $dstKey - 结果保存在该key
  703. * @param string $key1
  704. * @param string $key2
  705. * @return boolean|int 成功返回$dstKey集合元素个数, 失败返回false
  706. */
  707. public function sUnionStore($dstkey, $key1, $key2)
  708. {
  709. if (func_num_args() < 2) {
  710. return false;
  711. }
  712. return call_user_func_array([$this->_redis, "sUnionStore"], func_get_args());
  713. }
  714. /**
  715. * 有序集合操作 - 添加元素
  716. * @param string $key
  717. * @param mixed $value
  718. * @param double $score - 元素权值
  719. * @param int $expire - 超时时间, 0不限制
  720. * @return bool 成功返回true
  721. */
  722. public function zAdd($key, $value, $score, $expire = 0)
  723. {
  724. $ret = $this->_redis->zAdd($key, $score, $value);
  725. if ($ret && $expire > 0) {
  726. $this->expire($key, $expire);
  727. }
  728. return $ret ? true : false;
  729. }
  730. /**
  731. * 有序集合操作 - 批量添加元素
  732. * @param string $key
  733. * @param array $value - 集合元素数组,格式: ["元素1" => "权值", "元素2" => "权值"]
  734. * @param int $expire - 超时时间, 0不限制
  735. * @return bool 成功返回true
  736. */
  737. public function zAdds($key, array $values, $expire = 0)
  738. {
  739. if (empty($values) || !is_array($values)) {
  740. return false;
  741. }
  742. $params = [$key];
  743. foreach ($values as $k => $score) {
  744. $params[] = $score;
  745. $params[] = $k;
  746. }
  747. $ret = call_user_func_array([$this->_redis, 'zAdd'], $params);
  748. if ($ret && $expire > 0) {
  749. $this->expire($key, $expire);
  750. }
  751. return $ret ? true : false;
  752. }
  753. /**
  754. * 有序集合操作 - 返回集合元素个数
  755. * @param string $key
  756. * @return int
  757. */
  758. public function zSize($key)
  759. {
  760. return $this->_redis->zSize($key);
  761. }
  762. /**
  763. * 有序集合操作 - 统计权值在[$start, $end]之间的元素个数
  764. * @param string $key
  765. * @param string $start - 权值最小值, 支持无穷小, Redis::MIN_VALUE
  766. * @param string $end - 权值最大值, 支持无穷大, Redis::MAX_VALUE
  767. * @return int
  768. */
  769. public function zCount($key, $start, $end)
  770. {
  771. return $this->_redis->zCount($key, $start, $end);
  772. }
  773. /**
  774. * 有序集合操作 - 指定元素的增加权值
  775. * @param string $key
  776. * @param mixed $member - 集合元素
  777. * @param double $score - 需要增加的权值
  778. * @param int $expire - 超时时间, 0不限制
  779. * @return int 成功返回新的权值
  780. */
  781. public function zIncrBy($key, $member, $score, $expire = 0)
  782. {
  783. $ret = $this->_redis->zIncrBy($key, $score, $member);
  784. if (false !== $ret && $expire > 0) {
  785. $this->expire($key, $expire);
  786. }
  787. return $ret;
  788. }
  789. /**
  790. * 有序集合操作 - 返回[start, end]索引区间的元素, 升序排序
  791. * @param string $key
  792. * @param int $start - 开始索引
  793. * @param int $end - 结束索引, -1代表最后一个
  794. * @return array | false 成功返回集合元素数组,格式: ["元素1" => 权值, "元素2" => 权值 ...]
  795. */
  796. public function zRange($key, $start, $end)
  797. {
  798. return $this->_redis->zRange($key, $start, $end, true);
  799. }
  800. /**
  801. * 有序集合操作 - 返回[start, end]索引区间的元素, 反序排序
  802. * @param string $key
  803. * @param int $start - 开始索引
  804. * @param int $end - 结束索引, -1代表最后一个
  805. * @return array | false 成功返回集合元素数组,格式: ["元素1" => 权值, "元素2" => 权值 ...]
  806. */
  807. public function zRevRange($key, $start, $end)
  808. {
  809. return $this->_redis->zRevRange($key, $start, $end, true);
  810. }
  811. /**
  812. * 有序集合操作 - 交集运算,合并相同元素权值时采用如下策略:
  813. * 1. $weights为空, 则权值相加,$aggregateType设置无效
  814. * 2. $weights不为空,且$weights数组大小必须与$keys数组大小一致,否则失败。
  815. * 这种情况下,首先$keys数组中的每一个集合的元素权值分别乘于$weights对应的权值,然后根据$aggregateType确定相加,取最大值或则最小值.
  816. * 例子:
  817. * //创建有序集合,zuser_list1
  818. * Redis::getInstance()->zAdds("zuser_list1", [
  819. * //元素 => 权值
  820. * 1 => 10,
  821. * 2 => 5,
  822. * 3 => 13,
  823. * 6 => 1,
  824. * 9 => 2,
  825. * 10 => 1,
  826. * ]);
  827. * //创建有序集合,zuser_list2
  828. * Redis::getInstance()->zAdds("zuser_list2", [
  829. * 1 => 10,
  830. * 2 => 5,
  831. * 3 => 13,
  832. * 60 => 1,
  833. * ]);
  834. * // 集合zuser_list1和zuser_list2做交集运算, 结果保存在zuser_dst中
  835. * Redis::getInstance()->zInter("zuser_dst", array("zuser_list1", "zuser_list2"), [1,10], Redis::AGGREGATE_TYPE_SUM);
  836. * //结果为:[
  837. * //元素 => 权值
  838. * 2 => 55,
  839. * 1 => 110,
  840. * 3 => 143,
  841. * ]
  842. * //计算过程:
  843. * 首先 zuser_list1和zuser_list2直接做交集运算,遇到相同的元素按下面规则处理
  844. * 因为$weights权值数组为: [1, 10], 因此zuser_list1集合每个元素的权值乘于 1, zuser_list2集合每个元素的权值乘于 10
  845. * 因为$aggregateType = Redis::AGGREGATE_TYPE_SUM, 所以相同元素权值相加。
  846. *
  847. * @param string $dstKey - 结果保存在该key
  848. * @param array $keys - 需要做交集运算的集合key数组
  849. * @param array $weights - 权值数组,必须与keys数组的大小一致,要么就为空
  850. * @param string $aggregateType - 相同元素的权值聚合类型,Redis::AGGREGATE_TYPE_SUM 求和
  851. * Redis::AGGREGATE_TYPE_MAX 取最大值
  852. * Redis::AGGREGATE_TYPE_MIN 取最小值
  853. * @return int 成功返回$dstKey结果元素个数
  854. */
  855. public function zInter($dstKey, array $keys, array $weights = [], $aggregateType = self::AGGREGATE_TYPE_SUM)
  856. {
  857. if (empty($weights)) {
  858. return $this->_redis->zinterstore($dstKey, $keys);
  859. }
  860. return $this->_redis->zinterstore($dstKey, $keys, $weights, $aggregateType);
  861. }
  862. /**
  863. * 有序集合操作 - 返回权值区间 [start,end]的集合元素, 权值按小到大排序
  864. * @param string $key
  865. * @param string $start - 权值最小值, 支持无穷小, Redis::MIN_VALUE
  866. * @param string $end - 权值最大值, 支持无穷大, Redis::MAX_VALUE
  867. * @param int $offset - 开始偏移
  868. * @param int $count - 分页大小
  869. * @return array | false 格式:[
  870. * "元素1" => 权值,
  871. * "元素2" => 权值,
  872. * ....
  873. * ]
  874. */
  875. public function zRangeByScore($key, $start, $end, $offset = 0, $count = 0)
  876. {
  877. if ($offset >= 0 && $count > 0) {
  878. return $this->_redis->zRangeByScore($key, $start, $end, ['withscores' => true, 'limit' => [$offset, $count]]);
  879. }
  880. return $this->_redis->zRangeByScore($key, $start, $end, ['withscores' => true]);
  881. }
  882. /**
  883. * 有序集合操作 - 返回权值区间 [start,end]的集合元素, 权值按大到小排序
  884. * @param string $key
  885. * @param string $start - 权值最小值, 支持无穷小, Redis::MIN_VALUE
  886. * @param string $end - 权值最大值, 支持无穷大, Redis::MAX_VALUE
  887. * @param int $offset - 开始偏移
  888. * @param int $count - 分页大小
  889. * @return array | false 格式:[
  890. * "元素1" => 权值,
  891. * "元素2" => 权值,
  892. * ....
  893. * ]
  894. */
  895. public function zRevRangeByScore($key, $start, $end, $offset = 0, $count = 0)
  896. {
  897. if ($offset >= 0 && $count > 0) {
  898. return $this->_redis->zRevRangeByScore($key, $end, $start, ['withscores' => true, 'limit' => [$offset, $count]]);
  899. }
  900. return $this->_redis->zRevRangeByScore($key, $end, $start, ['withscores' => true]);
  901. }
  902. /**
  903. * 有序集合操作 - 假定集合元素权值相等的情况下,集合元素按字典顺序查找
  904. * 例子:
  905. * //查找小于等于y的集合元素
  906. * Redis::getInstance()->zRangeByLex("key1", "-", "[y")
  907. * //查找大于c的元素
  908. * Redis::getInstance()->zRangeByLex("key1", "(c", "+")
  909. *
  910. * @param string $key
  911. * @param string $min - 字母最小值,- 表示负无穷,( 表示大于,[ 表示大于等于
  912. * @param string $max - 字母最大值, + 表示正无穷,( 表示大于,[ 表示大于等于
  913. * @param int $offset - 元素开始偏移
  914. * @param int $count - 分页大小
  915. * @return
  916. */
  917. public function zRangeByLex($key, $min, $max, $offset = 0, $count = 0)
  918. {
  919. if ($offset >= 0 && $count > 0) {
  920. return $this->_redis->zRangeByLex($key, $min, $max, $offset, $count);
  921. }
  922. return $this->_redis->zRangeByLex($key, $min, $max);
  923. }
  924. /**
  925. * 有序集合操作 - 查找正序排名,从0开始计算名次
  926. * @param string $key
  927. * @param mixed $member - 集合元素
  928. * @return int | false 成功返回名次
  929. */
  930. public function zRank($key, $member)
  931. {
  932. return $this->_redis->zRank($key,$member);
  933. }
  934. /**
  935. * 有序集合操作 - 查找反序排名,从0开始计算名次
  936. * @param string $key
  937. * @param mixed $member - 集合元素
  938. * @return int | false 成功返回名次
  939. */
  940. public function zRevRank($key, $member)
  941. {
  942. return $this->_redis->zRevRank($key,$member);
  943. }
  944. /**
  945. * 有序集合操作 - 删除集合元素
  946. * @param string $key
  947. * @param mixed $member - 集合元素, 支持批量删除,传递数组即可
  948. * @return int 返回删除元素个数
  949. */
  950. public function zRem($key, $member)
  951. {
  952. if (!empty($member) && is_array($member)) {
  953. $params = [$key];
  954. $params = array_merge($params, $member);
  955. return call_user_func_array([$this->_redis, 'zRem'], $params);
  956. }
  957. return $this->_redis->zRem($key, $member);
  958. }
  959. /**
  960. * 有序集合操作 - 删除这个名次区间[start,end]的元素, 按升序排序
  961. * @param string $key
  962. * @param int $start
  963. * @param int $end
  964. * @return int | false 成功返回删除元素个数
  965. */
  966. public function zRemRangeByRank($key, $start, $end)
  967. {
  968. return $this->_redis->zRemRangeByRank($key, $start, $end);
  969. }
  970. /**
  971. * 有序集合操作 - 删除这个权值区间[start,end]的元素
  972. * @param string $key
  973. * @param string $start - 权值最小值, 支持无穷小, Redis::MIN_VALUE
  974. * @param string $end - 权值最大值, 支持无穷大, Redis::MAX_VALUE
  975. * @return int | false 成功返回删除元素个数
  976. */
  977. public function zRemRangeByScore($key, $start, $end)
  978. {
  979. return $this->_redis->zRemRangeByScore($key, $start, $end);
  980. }
  981. /**
  982. * 有序集合操作 - 获取指定元素的权值
  983. * @param string $key
  984. * @param string $member - 元素
  985. * @return double | false 成功返回权值,失败返回false
  986. */
  987. public function zScore($key, $member)
  988. {
  989. return $this->_redis->zScore($key, $member);
  990. }
  991. /**
  992. * 有序集合操作 - 并集运算,遇到相同元素合并权值策略,请参考zInter交集权值合并策略。
  993. * @param string $dstKey - 结果保存在该key
  994. * @param array $keys - 需要做并集运算的集合key数组
  995. * @param array $weights - 权值数组,必须与keys数组的大小一致,要么就为空
  996. * @param string $aggregateType - 相同元素的权值聚合类型,Redis::AGGREGATE_TYPE_SUM 求和
  997. * Redis::AGGREGATE_TYPE_MAX 取最大值
  998. * Redis::AGGREGATE_TYPE_MIN 取最小值
  999. * @return int 成功返回$dstKey结果元素个数
  1000. */
  1001. public function zUnion($dstKey, array $keys, array $weights = [], $aggregateType = self::AGGREGATE_TYPE_SUM)
  1002. {
  1003. if (empty($weights)) {
  1004. return $this->_redis->zunionstore($dstKey, $keys);
  1005. }
  1006. return $this->_redis->zunionstore($dstKey, $keys, $weights, $aggregateType);
  1007. }
  1008. /**
  1009. * {@inheritDoc}
  1010. * @see CCache::addValue()
  1011. */
  1012. protected function addValue($key, $value, $expire)
  1013. {
  1014. return $this->setNx($key, $value, $expire);
  1015. }
  1016. /**
  1017. * {@inheritDoc}
  1018. * @see CCache::deleteValue()
  1019. */
  1020. protected function deleteValue($key)
  1021. {
  1022. return $this->delete($key);
  1023. }
  1024. /**
  1025. * {@inheritDoc}
  1026. * @see CCache::flushValues()
  1027. */
  1028. protected function flushValues()
  1029. {
  1030. //不支持,禁用
  1031. return true;
  1032. }
  1033. /**
  1034. * {@inheritDoc}
  1035. * @see CCache::generateUniqueKey()
  1036. */
  1037. protected function generateUniqueKey($key)
  1038. {
  1039. return $key;
  1040. }
  1041. /**
  1042. * {@inheritDoc}
  1043. * @see CCache::getValue()
  1044. */
  1045. protected function getValue($key)
  1046. {
  1047. return $this->get($key);
  1048. }
  1049. /**
  1050. * {@inheritDoc}
  1051. * @see CCache::getValues()
  1052. */
  1053. protected function getValues($keys)
  1054. {
  1055. return $this->mget($keys);
  1056. }
  1057. /**
  1058. * {@inheritDoc}
  1059. * @see CCache::setValue()
  1060. */
  1061. protected function setValue($key, $value, $expire)
  1062. {
  1063. return $this->set($key, $value, $expire);
  1064. }
  1065. /**
  1066. * 连接redis
  1067. */
  1068. private function _connect()
  1069. {
  1070. if (null === $this->_redis) {
  1071. $this->_redis = new \Redis();
  1072. }
  1073. $ret = false;
  1074. if ($this->_conf['persistent']) {
  1075. $ret = $this->_redis->pconnect($this->_conf['host'], $this->_conf['port'], $this->_conf['timeout']);
  1076. } else {
  1077. $ret = $this->_redis->connect($this->_conf['host'], $this->_conf['port'], $this->_conf['timeout']);
  1078. }
  1079. //密码不为空, 则需要密码验证
  1080. if (!empty($this->_conf['password'])) {
  1081. $ret = $this->_redis->auth($this->_conf['password']);
  1082. }
  1083. // 这里防止测试环境redis串数据
  1084. if (LWM_ENV == 'dev') {
  1085. $this->_redis->select(1);
  1086. }
  1087. //序列化
  1088. $this->_redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
  1089. return $ret;
  1090. }
  1091. }