CRedisUtil.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. <?php
  2. namespace loyalsoft;
  3. define('Redis_Debug', true); // 调试redis操作
  4. //require __DIR__ . '/Predis/Autoloader.php';
  5. require __DIR__ . '/predis-2.0.0/src/Autoloader.php'; # 2022.8.16 更新Predis代码到2.0
  6. \Predis\Autoloader::register();
  7. /**
  8. * redis操作封装,
  9. * 关于阿里云redis的支持命令和未开放命令见:
  10. * https://docs.aliyun.com/?spm=5176.7630237.9.3.WfKF0A#/pub/kvstore/quick-start/kvstore-redis-command
  11. * 腾讯云支持的命令:
  12. * https://www.qcloud.com/doc/product/239/%E4%BD%BF%E7%94%A8%E9%99%90%E5%88%B6
  13. * redis相关命令说明见:http://redisdoc.com/
  14. *
  15. * 支持命令集接口见: /phpRedisAdmin/predis/src/ClientInterface.php
  16. * @version <br/>
  17. * 1.0.4 取消公共基类CMemBase,后面可能不太会用到memcache(d)了. gwang 2020年11月23日
  18. * 1.0.3 扩展list相关api的操作方法, 针对values统一做json编解码处理.
  19. * 整理其他数据结构的操作方法, normal/hash/list api内部做json编解码处理,
  20. * set/zset value 默认不做json编解码处理, 针对set/zset的value,不推荐写入太大或复杂的数据.
  21. * gwang 2017年4月28日 <br/>
  22. * 1.0.2 扩充特有数据结构的操作方法, gwang 2016.4.21 <br/>
  23. * 1.0.1 扩充了事务的使用方法.开发竞争类业务,圣树争夺战, gwang 2016.3.21 <br/>
  24. * 1.0.0 pguan,基础功能, 方法与memcache看齐. <br/>
  25. */
  26. class CRedisUtil {
  27. // public $keyDic = null;
  28. // <editor-fold defaultstate="collapsed" desc="性能分析">
  29. static $caller_counter = array();
  30. /**
  31. * 调用统计
  32. */
  33. public static function AddCallCount() {
  34. self::$caller_counter[] = DebugHelper::get_call_stack(3, 2, true);
  35. }
  36. // </editor-fold>
  37. /**
  38. *
  39. * @var ClientInterface
  40. */
  41. public $redis = null;
  42. /**
  43. * 自动回收
  44. */
  45. function __destruct() {
  46. $this->close();
  47. }
  48. private static function debug() {
  49. if (defined('Redis_Debug') && Redis_Debug) {
  50. // DebugHelper::debug(DebugHelper::get_call_stack());
  51. self::AddCallCount();
  52. }
  53. }
  54. // <editor-fold defaultstate="collapsed" desc=" 实现CMemBase操作接口">
  55. /**
  56. * 添加一个值
  57. * @param string $key
  58. * @param string $value
  59. * @param int $ts=0 此值无效
  60. * @return true 成功, false 失败,此key已经存在
  61. */
  62. public function add($key, $value, $ts = 0) {
  63. self::debug();
  64. return $this->setnx($key, JsonUtil::encode($value));
  65. }
  66. /**
  67. * 复制一个变量到另一个key
  68. * @param string $surKey 源数据的key
  69. * @param string $desKey 目的数据的key
  70. */
  71. public function copy($surKey, $desKey) {
  72. self::debug();
  73. return $this->set($desKey, $this->get($surKey));
  74. }
  75. /**
  76. * 一次取多个值
  77. * @param array(string) $keys
  78. * @return array
  79. */
  80. public function getMulti($keys) {
  81. self::debug();
  82. // var_dump($keys);
  83. return $this->mget($keys);
  84. }
  85. /**
  86. * 设置多个值
  87. * @param dic $dict [{"key":value},{"key":value},....]
  88. * @return true 永远成功
  89. */
  90. public function setMutlti($dict) {
  91. self::debug();
  92. $params = array();
  93. foreach ($dict as $key => $val) {
  94. $params[$key] = is_string($val) ? $val : JsonUtil::encode($val);
  95. }
  96. if (count($params) <= 0) {
  97. return TRUE;
  98. }
  99. $this->mset($params);
  100. return true;
  101. }
  102. /**
  103. * 替换某个值
  104. * @param string $key
  105. * @param string $value
  106. * @param int $ts
  107. * @return boolean true 成功,false 失败
  108. */
  109. public function replace($key, $value, $ts = 0) {
  110. self::debug();
  111. $ret = $this->redis->setex($key, $value, $ts);
  112. if (strtolower($ret) == "ok") {
  113. return true;
  114. }
  115. $this->logErr("replace" . $ret);
  116. return false;
  117. }
  118. /**
  119. * 不经过jsonencode直接存储
  120. * @deprecated since version 20160413113950 经过自己考察json_encode对数据的影响并不存在
  121. * @param type $key
  122. * @return any
  123. */
  124. public function getWithoutJson($key) {
  125. self::debug();
  126. return $this->redis->get($key);
  127. }
  128. /**
  129. * 不经过jsondecode直接返回
  130. * @deprecated since version 20160413113950 经过自己考察json_encode对数据的影响并不存在
  131. * @param string $key
  132. * @param string $value
  133. * @param int $ts
  134. * @return boolean
  135. */
  136. public function setWithoutJson($key, $value, $ts = 0) {
  137. self::debug();
  138. $ret = $this->redis->set($key, $value, $ts);
  139. if (strtolower($ret) == "ok") {
  140. return true;
  141. }
  142. $this->logErr("set" . $ret);
  143. return false;
  144. }
  145. /**
  146. * 输出日志
  147. * @param mixed $msg
  148. */
  149. private function logErr($msg) {
  150. CLog::err($msg, "Redis Err:");
  151. }
  152. /**
  153. * 连接
  154. * @param string $host
  155. * @param string $port
  156. * @param string $pwd
  157. * @param string $db 数据库, 不建议输入参数, 如果是购买云实例只有一个db.
  158. * @return \CRedisUtil
  159. */
  160. public function conn($host, $port, $pwd = "", $db = 0) {
  161. // DebugHelper::print_stack_trace();
  162. // $this->redis = new \Predis\Client(array(
  163. // $this->redis = new \Redis();
  164. // $this->redis->connect('127.0.0.1', 6379);
  165. // $this->redis->auth($pwd);
  166. $this->redis = new \Predis\Client(array(
  167. 'scheme' => 'tcp',
  168. 'host' => $host,
  169. 'port' => $port,
  170. 'password' => $pwd,
  171. ));
  172. if ($db != 0) {
  173. $this->redis->select($db);
  174. }
  175. // $this->keyDic = new \stdClass();
  176. return $this;
  177. }
  178. /**
  179. * 关闭连接
  180. */
  181. public function close() {
  182. $this->redis->quit();
  183. }
  184. /**
  185. * 获取指定键值
  186. * @param string $key
  187. * @return any json_decode($result)
  188. */
  189. public function get($key) {
  190. self::debug();
  191. $result = $this->redis->get($key);
  192. if (!$result || $result == "" || $result == null) {
  193. return null;
  194. }
  195. // $this->keyDic->$key = $result;
  196. return JsonUtil::decode($result);
  197. }
  198. /**
  199. * 将字符串值 $val 关联到 key
  200. * @param string $key
  201. * @param any $value
  202. * @param int $ts default(0) 过期时间(单位秒)
  203. * @return boolean 成功true,失败false
  204. */
  205. public function set($key, $value, $ts = 0) {
  206. self::debug();
  207. if ($value === null || $value === "") { # 这里必须用全等符号
  208. return false;
  209. }
  210. if (is_string($value)) { # 使用json序列化后存储
  211. $val = $value;
  212. } else {
  213. $val = JsonUtil::encode($value);
  214. }
  215. if ($ts > 0) { # 将会设置TTL 到期删除 ps: replaced by gwang 增加过期时间
  216. $ret = $this->redis->setex($key, $ts, $val);
  217. } else { # 0:永不过期,如果原来有TTL将会清除TTL.
  218. $ret = $this->redis->set($key, $val);
  219. }
  220. if ("OK" != $ret) {
  221. $this->logErr("Set:" . $ret);
  222. return false;
  223. }
  224. return true;
  225. }
  226. /**
  227. * 安全的写入操作
  228. * @deprecated since version 1.0 云平台暂时不支持
  229. * @param string $key
  230. * @param any $value
  231. * @return boolean 成功true,失败false
  232. */
  233. public function cas($key, $value, $ts = 0) {
  234. if (false) { # ps. 各云平台皆不支持eval方法执行lua脚本.等开放支持的时候才是真正支持cas的时候
  235. $castoken = $this->keyDic->$key;
  236. # # 定义一段脚本
  237. $script = <<<casscript
  238. if redis.call("get",KEYS[1]) == "$castoken"
  239. then
  240. return redis.call("set",KEYS[1],ARGV[1])
  241. else
  242. return 0
  243. end
  244. casscript;
  245. $ret = $this->redis->eval($script, 1, $key, $value); # redis 执行lua脚本
  246. if (0 == $ret) {
  247. return false;
  248. }
  249. return true;
  250. }
  251. // 非线程安全,原因见下
  252. return $this->set($key, $value, $ts);
  253. }
  254. /**
  255. * 删除一个指定键值
  256. * @param string $key
  257. * @return int 删除键的个数
  258. */
  259. public function delete($key) {
  260. self::debug();
  261. my_Assert(is_string($key), "arg key should be a string!");
  262. $infos = array();
  263. array_push($infos, $key);
  264. return $this->redis->del($infos);
  265. }
  266. /**
  267. * 删除一个或多个指定键值
  268. * @param array $keys
  269. * @return int 删除键的个数
  270. */
  271. public function deleteMulti($keys) {
  272. self::debug();
  273. $infos = (array) $keys; # 强制转数据类型为数组
  274. return $this->redis->del($infos);
  275. }
  276. // </editor-fold>
  277. //
  278. // <editor-fold defaultstate="collapsed" desc=" normal 普通对象操作 mget/mset">
  279. /**
  280. * 返回所有(一个或多个)给定 key 的值
  281. * 如果给定的 key 里面,有某个 key 不存在,那么这个 key 返回特殊值 nil 。因此,该命令永不失败。
  282. * @param array $keys
  283. * @return array 一个包含所有给定 key 的值的列表
  284. */
  285. private function mget($keys) {
  286. // self::debug();
  287. $ret = array();
  288. if (count($keys)) {
  289. $ctx = $this->redis->mget($keys);
  290. $mval = count($ctx);
  291. for ($i = 0;
  292. $i < $mval;
  293. $i++) {
  294. $ret[] = JsonUtil::decode($ctx[$i]);
  295. }
  296. }
  297. return $ret;
  298. }
  299. /**
  300. * Add函数拥有相同效果 \n
  301. * 将 key 的值设为 value ,当且仅当 key 不存在。
  302. * 若给定的 key 已经存在,则不做任何动作。
  303. * @param type $key
  304. * @param type $val
  305. * @return boolean 成功true,失败false
  306. */
  307. private function setnx($key, $val) {
  308. self::debug();
  309. $ret = $this->redis->setnx($key, $val);
  310. // 成功返回1, 失败返回0
  311. if (1 == $ret) {
  312. return true;
  313. } else {
  314. $this->logErr("setnx:" . $ret . "(值已存在)");
  315. }
  316. return false;
  317. }
  318. /**
  319. * 同时设置一个或多个 key-value 对
  320. * 如果某个给定 key 已经存在,那么 MSET 会用新值覆盖原来的旧值
  321. * @param array $dict
  322. * @return mixed
  323. */
  324. private function mset($dict) {
  325. self::debug();
  326. return $this->redis->mset($dict);
  327. }
  328. /**
  329. * 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在
  330. * 即使只有一个给定 key 已存在, MSETNX 也会拒绝执行所有给定 key 的设置操作
  331. *
  332. * @param array $dict
  333. * @return int
  334. */
  335. public function msetnx($dict) {
  336. self::debug();
  337. $ret = $this->redis->msetnx($dict);
  338. return $ret == 1;
  339. }
  340. /**
  341. * 检测指定键值是否存在
  342. * @param type $key
  343. * @return boolean true 存在, false 不存在
  344. */
  345. public function exists($key) {
  346. self::debug();
  347. return $this->redis->exists($key) == 1;
  348. }
  349. /**
  350. * 将 key 中储存的数字值增一
  351. * 如果 key 不存在,那么 key 的值会先被初始化为 0
  352. * 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误
  353. * 本操作的值限制在 64 位(bit)有符号数字表示之内
  354. * @param type $key
  355. * @return int 执行 INCR 命令之后 key 的值
  356. */
  357. public function increment($key) {
  358. self::debug();
  359. return $this->redis->incr($key);
  360. }
  361. /**
  362. * 将 key 中储存的数字值增加 一个int值
  363. * 如果 key 不存在,那么 key 的值会先被初始化为 0
  364. * 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误
  365. * 本操作的值限制在 64 位(bit)有符号数字表示之内
  366. * @param string $key
  367. * @param int $i 增加的值
  368. * @return int 执行 INCR 命令之后 key 的值
  369. */
  370. public function incrby($key, $i) {
  371. self::debug();
  372. return $this->redis->incrby($key, $i);
  373. }
  374. // </editor-fold>
  375. //
  376. //======================== 以下部分 added by gwang at 2016-4-14 15:17:25 =================
  377. // <editor-fold defaultstate="collapsed" desc=" 辅助函数 ">
  378. /**
  379. * Server功能,看服务器是否连通
  380. * @return boolean true连通正常
  381. */
  382. public function ping() {
  383. $ret = $this->redis->ping();
  384. if ($ret == "PONG") {
  385. return true;
  386. }
  387. $this->logErr("ping:" . $ret);
  388. return false;
  389. }
  390. /**
  391. * 对数组进行json编码
  392. * @param array $values
  393. * @return array
  394. */
  395. static private function json_encode_arr($values) {
  396. $arr = array();
  397. if (is_array($values)) {
  398. $arr = array_map(function ($v) {
  399. return JsonUtil::encode($v);
  400. }, $values);
  401. } else {
  402. $arr[] = JsonUtil::encode($values);
  403. }
  404. return $arr;
  405. }
  406. /**
  407. * 对数组进行json解码
  408. * @param array $values
  409. * @return array
  410. */
  411. static private function json_decode_arr(array $values) {
  412. $arr = array();
  413. if (is_array($values)) {
  414. $arr = array_map(function ($v) {
  415. return JsonUtil::decode($v);
  416. }, $values);
  417. } else {
  418. $arr[] = JsonUtil::decode($values);
  419. }
  420. return $arr;
  421. }
  422. // </editor-fold>
  423. //
  424. // <editor-fold defaultstate="collapsed" desc=" 事务操作 ">
  425. /**
  426. * 监视一个(或多个) key ,如果在事务执行之前这个(或这些) key 被其他命令所改动,那么事务将被打断。
  427. * @param string $key
  428. */
  429. public function watch($key) {
  430. $this->redis->watch($key);
  431. }
  432. /**
  433. * 取消监视
  434. */
  435. public function unwatch() {
  436. $this->redis->unwatch();
  437. }
  438. /**
  439. * 开启事务
  440. */
  441. public function multi() {
  442. $this->redis->multi();
  443. }
  444. /**
  445. * 执行事务
  446. * @return type 事务块内所有命令的返回值,按命令执行的先后顺序排列。当操作被打断时,返回空值 nil 。
  447. */
  448. public function exec() {
  449. return $this->redis->exec();
  450. }
  451. // </editor-fold>
  452. //
  453. // == ↓ 下面是Redis独有的数据类型操作 ↓ ==
  454. //
  455. // <editor-fold defaultstate="collapsed" desc=" set 集合操作 ">
  456. /**
  457. * 集合(set) - 将一个或多个 member 元素加入到集合 key 当中,已经存在于集合的 member 元素将被忽略。
  458. * 集合不存在时将会创建集合
  459. * @param string $key
  460. * @param string[] $members (mixed is ok, i will transmit it.)
  461. * @return int
  462. * @expectedException type not set error
  463. */
  464. public function sadd($key, $members) {
  465. self::debug();
  466. if (!is_array($members)) { # 防御: 参数不为数组
  467. if (!is_string($members)) { # 防御: 参数不为字符串
  468. $members = JsonUtil::encode($members);
  469. }
  470. $members = array($members); # 转为字符串数组
  471. }
  472. return $this->redis->sadd($key, $members);
  473. }
  474. /**
  475. * 集合(set) - 将一个或多个 member 元素从集合 key 当中移除
  476. * 集合不存在时将会创建集合
  477. * @param string $key
  478. * @param string[] $members
  479. * @return int
  480. * @expectedException type not set error
  481. */
  482. public function sremove($key, $members) {
  483. self::debug();
  484. return $this->redis->srem($key, $members);
  485. }
  486. /**
  487. * 集合(set) - 返回集合 key 的基数(集合中元素的数量)。
  488. * @param strig $key
  489. * @return int
  490. */
  491. public function scard($key) {
  492. self::debug();
  493. return $this->redis->scard($key);
  494. }
  495. /**
  496. * 集合(set) - 等效于scard: 返回集合 key 的基数(集合中元素的数量)。
  497. * @param string $key
  498. * @return int
  499. *
  500. */
  501. public function slen($key) {
  502. self::debug();
  503. return $this->scard($key);
  504. }
  505. /**
  506. * 集合(set) - 判断某个元素是否属于集合
  507. * @param string $key
  508. * @param string $member
  509. * @return bool
  510. */
  511. public function sismember($key, $member) {
  512. self::debug();
  513. return $this->redis->sismember($key, $member) == 1;
  514. }
  515. /**
  516. * 集合(set) - 返回集合 key 中的所有成员。
  517. * @param type $key
  518. * @return array 不存在的key视为空集合
  519. */
  520. public function smembers($key) {
  521. self::debug();
  522. return $this->redis->smembers($key);
  523. }
  524. /**
  525. * 集合(set) - 如果命令执行时,只提供了 key 参数,那么返回集合中的10个随机元素。
  526. * 如果 count 为正数,且小于集合基数,那么命令返回一个包含 count 个元素的数组,数组中的元素各不相同。如果 count 大于等于集合基数,那么返回整个集合。
  527. * 如果 count 为负数,那么命令返回一个数组,数组中的元素可能会重复出现多次,而数组的长度为 count 的绝对值。
  528. * @param string $key
  529. * @param int $count =10
  530. * @return array
  531. */
  532. public function srandmember($key, $count = 10) {
  533. self::debug();
  534. return $this->redis->srandmember($key, $count);
  535. }
  536. // </editor-fold>
  537. //
  538. // <editor-fold defaultstate="collapsed" desc=" hash 哈希表操作 ">
  539. /**
  540. * 哈希表 - 删除 字段
  541. * @param string $key
  542. * @param array $fields
  543. * @return int 删除的字段的数量
  544. */
  545. public function hdel($key, $fields) {
  546. self::debug();
  547. return $this->redis->hdel($key, $fields);
  548. }
  549. /**
  550. * 哈希表 - 判断field是否存在
  551. * @param string $key
  552. * @param string $field
  553. * @return boolean true=存在,false 找不到
  554. */
  555. public function hexists($key, $field) {
  556. self::debug();
  557. return $this->redis->hexists($key, $field) == 1;
  558. }
  559. /**
  560. * 哈希表 - 获取字段
  561. * @param string $key
  562. * @param string $field 字段名
  563. * @return mixed json_decoded object
  564. */
  565. public function hget($key, $field) {
  566. self::debug();
  567. $ret = $this->redis->hget($key, $field);
  568. return JsonUtil::decode($ret);
  569. }
  570. /**
  571. * 哈希表 - 获取所有字段
  572. * @param string $key
  573. * @return stdclass/associate_array (适用箭头取变量写法)
  574. */
  575. public function hgetall($key) {
  576. self::debug();
  577. $ret = ArrayInit();
  578. $arr = $this->redis->hgetall($key);
  579. foreach ($arr as $k => $v) {
  580. $ret[$k] = JsonUtil::decode($v);
  581. }
  582. // 转为关联数组({})再返回, 方便代码中使用箭头写法
  583. return JsonUtil::decode(JsonUtil::encode($ret));
  584. }
  585. /**
  586. * 哈希表 - 获取表中字段数量
  587. * @param string $key
  588. * @return int
  589. */
  590. public function hlen($key) {
  591. self::debug();
  592. return $this->redis->hlen($key);
  593. }
  594. /**
  595. * 哈希表 - 同时获取多个字段
  596. * @param string $key
  597. * @param array $fields
  598. * @return Array
  599. */
  600. public function hmget($key, $fields) {
  601. self::debug();
  602. $ret = ArrayInit();
  603. if (is_array($fields) && count($fields) > 0) {
  604. $arr = $this->redis->hmget($key, $fields);
  605. foreach ($arr as $k => $v) {
  606. $ret[$k] = JsonUtil::decode($v);
  607. }
  608. }
  609. // 转为关联数组({})再返回, 方便代码中使用箭头写法
  610. return JsonUtil::decode(JsonUtil::encode($ret));
  611. }
  612. /**
  613. * 哈希表 - 同时设置多个字段的值
  614. * @param string $key
  615. * @param assoc_array $dictionary
  616. * @return boolean true成功
  617. */
  618. public function hmset($key, $dictionary) {
  619. self::debug();
  620. $newdic = ArrayInit();
  621. foreach ($dictionary as $k => $v) {
  622. $newdic[$k] = JsonUtil::encode($v);
  623. }
  624. $ret = $this->redis->hmset($key, $newdic);
  625. if (strtolower($ret) == 'ok') {
  626. return true;
  627. }
  628. return false;
  629. }
  630. /**
  631. * 哈希表 - 同时设置多个字段的值(带Not Changed校验)
  632. * @param string $key
  633. * @param HashSaver $dic (要包含$stVer字段用以校验)
  634. * @return boolean 写入是否成功
  635. */
  636. public function hmset_Cas(string $key, HashSaver $dic) {
  637. # # 定义一段脚本
  638. static $script = <<<Lua
  639. local key,casToken,casVer, dic = KEYS[1], KEYS[2], ARGV[1], ARGV[2]
  640. local cv = redis.call("hget", key, casToken)
  641. local t = cjson.decode( dic )
  642. if not cv or tonumber(cv) < tonumber(casVer) then
  643. for k, v in pairs(t) do
  644. if type(v) =="table" then -- 加戏,如果value是对象的话, 继续encode一下.
  645. v=cjson.encode(v)
  646. end
  647. redis.call("hset", key, k, v)
  648. end
  649. return 1
  650. else
  651. return 0
  652. end
  653. Lua;
  654. try {
  655. $castoken = "stVer";
  656. $casVer = $dic->stVer;
  657. // CLog::err($dic->toString());
  658. $ret = $this->redis->eval($script, 2, $key, $castoken, $casVer, $dic->toString()); # redis 执行lua脚本
  659. // CLog::err($dic->toString());
  660. if (0 == $ret) {
  661. return false;
  662. }
  663. } catch (\Exception $e) {
  664. CLog::err($e->getMessage());
  665. return false;
  666. }
  667. return true;
  668. }
  669. /**
  670. * 哈希表 - 设置或新建一个字段的值
  671. * @param string $key
  672. * @param string $field
  673. * @param $mixed $value
  674. * @return int 0 覆盖旧值, 1 新建字段
  675. */
  676. public function hset($key, $field, $value) {
  677. self::debug();
  678. return $this->redis->hset($key, $field, JsonUtil::encode($value));
  679. }
  680. /**
  681. * 哈希表 - 增加一个新的field,已经存在则放弃操作返回false
  682. * @param string $key
  683. * @param string $field
  684. * @param string $value
  685. * @return boolean true成功
  686. */
  687. public function hsetnx($key, $field, $value) {
  688. self::debug();
  689. return $this->redis->hsetnx($key, $field, JsonUtil::encode($value)) == 1;
  690. }
  691. /**
  692. * 哈希表 - 按字段赠加 int值
  693. * @param string $key
  694. * @param string $field
  695. * @param int $increment
  696. * @return int
  697. */
  698. public function hincrby($key, $field, $increment) {
  699. self::debug();
  700. return $this->redis->hincrby($key, $field, $increment);
  701. }
  702. /**
  703. * 哈希表 - 按字段增加 float值
  704. * @param string $key
  705. * @param string $field
  706. * @param string $increment float值用string
  707. * @return string 用string存float值
  708. */
  709. public function hincrbyfloat($key, $field, $increment) {
  710. self::debug();
  711. return $this->redis->hincrbyfloat($key, $field, $increment);
  712. }
  713. /**
  714. * @param string $key
  715. * @return array
  716. */
  717. public function hkeys($key) {
  718. self::debug();
  719. return $this->redis->hkeys($key);
  720. }
  721. // * @method array hscan($key, $cursor, array $options = null)
  722. // * @method array hvals($key)
  723. // </editor-fold>
  724. //
  725. // <editor-fold defaultstate="collapsed" desc=" list 链表操作 ">
  726. //
  727. // <editor-fold defaultstate="collapsed" desc=" 阻塞的链表操作 ">
  728. /**
  729. * 链表 - 阻塞弹出, 当列表中没有元素的时候,命令会阻塞,直到等待超时或者有元素被添加到列表中.
  730. * @param array $keys 可以指定多个数组
  731. * @param int $timeout
  732. * @return array
  733. */
  734. public function blpop(array $keys, $timeout) {
  735. self::debug();
  736. $arr = $this->redis->blpop($keys, $timeout);
  737. $arr[1] = JsonUtil::decode($arr[1]); // 对value进行解包
  738. return $arr;
  739. }
  740. /**
  741. * 链表 - 阻塞队尾弹出, 当列表中没有元素的时候,命令会阻塞,直到等待超时或者有元素被添加到列表中.
  742. * @return array
  743. */
  744. public function brpop(array $keys, $timeout) {
  745. self::debug();
  746. $arr = $this->redis->brpop($keys, $timeout);
  747. $arr[1] = JsonUtil::decode($arr[1]);
  748. return $arr;
  749. }
  750. /**
  751. * 链表 - 阻塞版的 队尾弹出插入到队首. 本操作是原子的.
  752. *
  753. * @return array 假如在指定时间内没有任何元素被弹出,则返回一个 nil 和等待时长。
  754. * 反之,返回一个含有两个元素的列表,第一个元素是被弹出元素的值,第二个元素是等待时长。
  755. */
  756. public function brpoplpush($source, $destination, $timeout) {
  757. self::debug();
  758. $arr = $this->redis > brpoplpush($source, $destination, $timeout);
  759. $arr[0] = JsonUtil::decode($arr[0]);
  760. return $arr;
  761. }
  762. // </editor-fold>
  763. //
  764. /**
  765. * 链表 - 返回下标为index的元素
  766. * @return string
  767. */
  768. public function lindex($key, $index) {
  769. self::debug();
  770. $a = $this->redis->lindex($key, $index);
  771. return JsonUtil::decode($a);
  772. }
  773. /**
  774. * 链表 - 返回 链表key的长度
  775. * @return int
  776. * @param type $key
  777. */
  778. public function llen($key) {
  779. self::debug();
  780. return $this->redis->llen($key);
  781. }
  782. /**
  783. * 链表 - 移除并返回链表的队首元素.
  784. * @return string
  785. * @param type $key
  786. */
  787. public function lpop($key) {
  788. self::debug();
  789. $a = $this->redis->lpop($key);
  790. return JsonUtil::decode($a);
  791. }
  792. /**
  793. * 链表 - 向链表插入一个或多个值,链表不存在时创建链表并插入元素
  794. * @return int key存在却不是链表类型时返回一个错误.
  795. * @param type $key
  796. * @param array $values
  797. */
  798. public function lpush($key, $values) {
  799. self::debug();
  800. $arr = self::json_encode_arr($values);
  801. return $this->redis->lpush($key, $arr);
  802. }
  803. /**
  804. * 链表 - 取链表中指定下标区间的元素
  805. * @return array
  806. * @param string $key
  807. * @param int $start
  808. * @param int $stop
  809. */
  810. public function lrange($key, $start, $stop) {
  811. self::debug();
  812. $values = $this->redis->lrange($key, $start, $stop);
  813. return self::json_decode_arr($values);
  814. }
  815. /**
  816. * 链表 - 移除链表中 count 个值为 value的元素.
  817. * @return int
  818. * @param string $key
  819. * @param int $count
  820. * @param string $value
  821. */
  822. public function lrem($key, $count, $value) {
  823. self::debug();
  824. return $this->redis->lrem($key, $count, JsonUtil::encode($value));
  825. }
  826. /**
  827. * 链表 - 将链表中下标为index的 元素设置为value
  828. * @return mixed
  829. *
  830. * @param type $key
  831. * @param type $index
  832. * @param type $value
  833. */
  834. public function lset($key, $index, $value) {
  835. self::debug();
  836. return $this->redis->lset($key, $index, JsonUtil::encode($value));
  837. }
  838. /**
  839. * 链表 - 对链表进行修剪, 让链表只保留指定下标区间的元素,其余元素删除
  840. * @return bool true 成功, false 失败
  841. * @param string $key
  842. * @param int $start
  843. * @param int $stop
  844. */
  845. public function ltrim($key, $start, $stop) {
  846. self::debug();
  847. // return mixed: ok or fails
  848. $ret = $this->redis->ltrim($key, $start, $stop);
  849. if (strtolower($ret) == 'ok') {
  850. return true;
  851. }
  852. return false;
  853. }
  854. /**
  855. * 链表 - 从链表右侧(尾部)弹出一个元素,并返回该元素
  856. * @param string $key
  857. * @return string 列表的尾元素。当 key 不存在时,返回 nil
  858. */
  859. public function rpop($key) {
  860. self::debug();
  861. return JsonUtil::decode($this->redis->rpop($key));
  862. }
  863. /**
  864. * 将一个或多个值 value 插入到列表 key 的表尾(最右边)。
  865. * @param string $key
  866. * @param array $values
  867. * @return int
  868. */
  869. public function rpush($key, array $values) {
  870. self::debug();
  871. $arr = self::json_encode_arr($values);
  872. return $this->redis->rpush($key, $arr);
  873. }
  874. //
  875. // /**
  876. // * 链表 - 向链表中插入一个或多个值,链表不存在时,什么也不做.
  877. // * @return int
  878. // * @param type $key
  879. // * @param type $value
  880. // */
  881. // public function lpushx($key, $value)
  882. // {
  883. // return $this->redis->lpushx($key, $value);
  884. // }
  885. // /**
  886. // * 链表 - 将值 value 插入到链表 key 中 , 位于pivot之前或之后
  887. // * @return int -1:未找到pivot, 0:链表为空或者不存在.
  888. // *
  889. // * @param string $key 链表名称
  890. // * @param string $whence after/before pivot之前或之后
  891. // * @param string $pivot 插入pivot之前或之后
  892. // * @param string $value 要插入的value
  893. // */
  894. // public function linsert($key, $whence, $pivot, $value)
  895. // {
  896. // $this->redis->linsert($key, $whence, $pivot, $value);
  897. // }
  898. // /**
  899. // * 在一个原子时间内,执行以下两个动作
  900. // * 将列表 source 中的最后一个元素(尾元素)弹出,并返回给客户端。
  901. // * 将 source 弹出的元素插入到列表 destination ,作为 destination 列表的的头元素.
  902. // * @return string
  903. // */
  904. // public function rpoplpush($source, $destination)
  905. // {
  906. // throw new Exception("un implemented now!");
  907. // }
  908. // /**
  909. // * 将值 value 插入到列表 key 的表尾,当且仅当 key 存在并且是一个列表。
  910. // * 和 RPUSH 命令相反,当 key 不存在时, RPUSHX 命令什么也不做。
  911. // * @param type $key
  912. // * @param type $value
  913. // * @return int
  914. // */
  915. // public function rpushx($key, $value)
  916. // {
  917. // throw new Exception("un implemented now!");
  918. // }
  919. // </editor-fold>
  920. //
  921. // <editor-fold defaultstate="collapsed" desc=" zset 有序集合 ">
  922. /**
  923. * 有序集合 - 添加或更新元素 对于zset类型不建议写入太长, 太复杂的value
  924. * @param string $key
  925. * @param array $membersAndScoresDictionary array( 'value'=>score,'value'=>score,...), score可以是int或float
  926. * @return int 新增元素数量,不包含更新的元素
  927. */
  928. public function zadd($key, $membersAndScoresDictionary) {
  929. self::debug();
  930. return $this->redis->zadd($key, $membersAndScoresDictionary);
  931. }
  932. /**
  933. * 有序集合 - 给某个元素增加积分
  934. * @param string $key
  935. * @param string $member
  936. * @param int $increment
  937. * @return string
  938. */
  939. public function zincrby($key, $member, $increment = 1) {
  940. self::debug();
  941. return $this->redis->zincrby($key, $increment, $member);
  942. }
  943. /**
  944. * 有序集合 - 元素数量
  945. * @param string $key
  946. * @return int
  947. */
  948. public function zlen($key) {
  949. self::debug();
  950. return $this->redis->zcard($key);
  951. }
  952. /**
  953. * 有序集合 - 统计某区间元素数量
  954. * @param string $key
  955. * @param int/float $min 最低分
  956. * @param int/float $max 最高分
  957. * @return int
  958. */
  959. public function zcount($key, $min, $max) {
  960. self::debug();
  961. return $this->redis->zcount($key, $min, $max);
  962. }
  963. /**
  964. * 有序集合 - 获取集合指定区间内的成员, 第一个成员从0开始
  965. * @param string $key
  966. * @param int $start
  967. * @param int $stop Ps.以 -1 表示最后一个成员, -2 表示倒数第二个成员
  968. * @param boolean $withScore 返回值中是否带score字段
  969. * @return array (index=>member) or assoc_array (member=>score)
  970. */
  971. public function zrange($key, $start, $stop, $withScore = false) {
  972. self::debug();
  973. if ($withScore) {
  974. return $this->redis->zrange($key, $start, $stop, 'WITHSCORES');
  975. } else {
  976. return $this->redis->zrange($key, $start, $stop);
  977. }
  978. if ($withScore) {
  979. $ret = $this->redis->zrange($key, $start, $stop, 'WITHSCORES');
  980. DebugHelper::var_dump($ret);
  981. $ma = count($ret);
  982. $arr = array();
  983. for ($i = 0; $i < $ma; $i += 2) {
  984. $arr[$ret[$i]] = $ret[$i + 1];
  985. }
  986. return $arr;
  987. } else {
  988. $ret = $this->redis->zrange($key, $start, $stop);
  989. DebugHelper::var_dump($ret);
  990. return $ret;
  991. }
  992. }
  993. /**
  994. *
  995. * 有序集合 - 获取集合倒序之后,指定区间内的成员, 第一个成员从0开始
  996. * @param string $key
  997. * @param int $start
  998. * @param int $stop Ps.以 -1 表示最后一个成员, -2 表示倒数第二个成员
  999. * @param boolean $withScore 返回值中是否带score字段 default(false)
  1000. * @return array (index=>member) or assoc_array (member=>score) 用foreach(=>)取
  1001. */
  1002. public function zrevrange($key, $start, $stop, $withScore = false) {
  1003. self::debug();
  1004. if ($withScore) {
  1005. $r = $this->redis->zrevrange($key, $start, $stop, 'WITHSCORES');
  1006. return $r;
  1007. } else {
  1008. return $this->redis->zrevrange($key, $start, $stop);
  1009. }
  1010. }
  1011. /**
  1012. *
  1013. * 有序列表 - 获取指定积分区间内的成员
  1014. * @param string $key
  1015. * @param int/float $min
  1016. * @param int/float $max
  1017. * @param boolean $withScore
  1018. * @param bool $limit 是否限制返回值大小
  1019. * @param int $offset 限制返回结果的起始位置
  1020. * @param type $count 返回结果的数量
  1021. * @return type
  1022. */
  1023. public function zrangebyscore($key, $min, $max, $withScore = false, $limit = false, $offset = 0, $count = 10) {
  1024. self::debug();
  1025. if ($limit) {
  1026. if ($withScore) {
  1027. return $this->redis->zrangebyscore($key, $min, $max, 'WITHSCORES', "LIMIT", $offset, $count);
  1028. } else {
  1029. return $this->redis->zrangebyscore($key, $min, $max, 'LIMIT', $offset, $count);
  1030. }
  1031. } else {
  1032. if ($withScore) {
  1033. return $this->redis->zrangebyscore($key, $min, $max, 'WITHSCORES');
  1034. } else {
  1035. return $this->redis->zrangebyscore($key, $min, $max);
  1036. }
  1037. }
  1038. }
  1039. /**
  1040. *
  1041. * 有序列表 - 获取按照倒序排序后指定积分区间内的成员
  1042. * @param string $key
  1043. * @param int/float $max
  1044. * @param int/float $min
  1045. * @param boolean $withScore
  1046. * @param bool $limit 是否限制返回值大小
  1047. * @param int $offset 限制返回结果的起始位置
  1048. * @param type $count 返回结果的数量
  1049. * @return type
  1050. */
  1051. public function zrevrangebyscore($key, $max, $min, $withScore = false, $limit = false, $offset = 0, $count = 10) {
  1052. self::debug();
  1053. if ($limit) {
  1054. if ($withScore) {
  1055. return $this->redis->zrevrangebyscore($key, $max, $min, 'WITHSCORES', "LIMIT", $offset, $count);
  1056. } else {
  1057. return $this->redis->zrevrangebyscore($key, $max, $min, 'LIMIT', $offset, $count);
  1058. }
  1059. } else {
  1060. if ($withScore) {
  1061. return $this->redis->zrevrangebyscore($key, $max, $min, 'WITHSCORES');
  1062. } else {
  1063. return $this->redis->zrevrangebyscore($key, $max, $min);
  1064. }
  1065. }
  1066. }
  1067. /**
  1068. * 有序列表 - 根据元素反查排名
  1069. * @param string $key
  1070. * @param string $member
  1071. * @return int
  1072. */
  1073. public function zrank($key, $member) {
  1074. self::debug();
  1075. return $this->redis->zrank($key, $member);
  1076. }
  1077. /**
  1078. * 有序列表 - 查询某个成员的倒序排名
  1079. * @param string $key
  1080. * @param string $member
  1081. * @return int
  1082. */
  1083. public function zrevrank($key, $member) {
  1084. self::debug();
  1085. return $this->redis->zrevrank($key, $member);
  1086. }
  1087. /**
  1088. * 有序列表 - 根据元素反查积分
  1089. * @param string $key
  1090. * @param string $member
  1091. * @return int/float
  1092. */
  1093. public function zscore($key, $member) {
  1094. self::debug();
  1095. return $this->redis->zscore($key, $member);
  1096. }
  1097. /**
  1098. * 有序列表 - 移除元素
  1099. * @param string $key
  1100. * @param string $member
  1101. */
  1102. public function zrem($key, $member) {
  1103. self::debug();
  1104. $this->redis->zrem($key, $member);
  1105. }
  1106. /**
  1107. * 有序列表 - 移除指定区间的元素
  1108. * @param string $key
  1109. * @param int $start
  1110. * @param int $stop
  1111. */
  1112. public function zremrangebyrank($key, $start, $stop) {
  1113. self::debug();
  1114. $this->redis->zremrangebyrank($key, $start, $stop);
  1115. }
  1116. /**
  1117. * 有序列表 - 移除指定积分区间的元素.
  1118. * @param string $key
  1119. * @param int/float $min
  1120. * @param int/float $max
  1121. */
  1122. public function zremrangebyscore($key, $min, $max) {
  1123. self::debug();
  1124. $this->redis->zremrangebyscore($key, $min, $max);
  1125. }
  1126. /**
  1127. * 有序列表 - 复制有序类表到一个新的key
  1128. * @param string $key_source 源集合
  1129. * @param string $key_new 目标集合
  1130. */
  1131. public function zcopy($key_source, $key_new) {
  1132. self::debug();
  1133. $this->redis->zunionstore($key_new, 1, $key_source);
  1134. }
  1135. // </editor-fold>
  1136. //
  1137. // <editor-fold defaultstate="collapsed" desc=" 其他api ">
  1138. //
  1139. /**
  1140. * 重命名一个key(注意: 与move的区别, move是将数据迁移到其他db,rename相当于在当前db内move)
  1141. * @param type $key
  1142. * @param type $newkey
  1143. * @return boolean
  1144. */
  1145. public function rename($key, $newkey) {
  1146. self::debug();
  1147. return $this->redis->rename($key, $newkey) == "ok";
  1148. }
  1149. /**
  1150. * 给指定的key设置/更新生存时间
  1151. * @param string $key
  1152. * @param number $seconds
  1153. * @return bool
  1154. */
  1155. public function expire($key, $seconds) {
  1156. self::debug();
  1157. return $this->redis->expire($key, $seconds) == "ok";
  1158. }
  1159. // == end of zSet ===
  1160. // * @method string zincrby($key, $increment, $member)
  1161. // * @method int zinterstore($destination, array $keys, array $options = null)
  1162. // * @method array zrevrangebyscore($key, $min, $max, array $options = null)
  1163. // * @method int zunionstore($destination, array $keys, array $options = null)
  1164. // * @method array zscan($key, $cursor, array $options = null)
  1165. // * @method array zrangebylex($key, $start, $stop, array $options = null)
  1166. // * @method int zremrangebylex($key, $min, $max)
  1167. // === end of zSet 操作 =====
  1168. // ======= hash 操作 ======
  1169. //
  1170. // // ======== set 操作 ======
  1171. // * @method array sdiff(array $keys)
  1172. // * @method int sdiffstore($destination, array $keys)
  1173. // * @method array sinter(array $keys)
  1174. // * @method int sinterstore($destination, array $keys)
  1175. //
  1176. // * @method int smove($source, $destination, $member)
  1177. // * @method string spop($key)
  1178. // * @method array sscan($key, $cursor, array $options = null)
  1179. // * @method array sunion(array $keys)
  1180. // * @method int sunionstore($destination, array $keys)
  1181. // ======= 订阅相关api =======s
  1182. // * @method int pfadd($key, array $elements)
  1183. // * @method mixed pfmerge($destinationKey, array $sourceKeys)
  1184. // * @method int pfcount(array $keys)
  1185. // * @method mixed pubsub($subcommand, $argument)
  1186. // * @method int publish($channel, $message)
  1187. // *
  1188. // ======= 事务相关api =======
  1189. // * @method mixed discard()
  1190. public function discard() {
  1191. return $this->redis->discard();
  1192. }
  1193. // * @method array exec()
  1194. // * @method mixed multi()
  1195. // * @method mixed unwatch()
  1196. // * @method mixed watch($key)
  1197. // ======= 执行lua脚本 =======
  1198. // * @method mixed eval($script, $numkeys, $keyOrArg1 = null, $keyOrArgN = null)
  1199. // * @method mixed evalsha($script, $numkeys, $keyOrArg1 = null, $keyOrArgN = null)
  1200. // * @method mixed script($subcommand, $argument = null)
  1201. // ======= 服务器操作api ======
  1202. // * @method mixed auth($password)
  1203. // * @method string echo($message)
  1204. // * @method mixed ping($message = null)
  1205. // * @method mixed select($database)
  1206. // * @method mixed bgrewriteaof()
  1207. // * @method mixed bgsave()
  1208. // </editor-fold>
  1209. }