PhpRedisConnection.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. <?php
  2. namespace Illuminate\Redis\Connections;
  3. use Closure;
  4. use Illuminate\Contracts\Redis\Connection as ConnectionContract;
  5. use RedisException;
  6. /**
  7. * @mixin \Redis
  8. */
  9. class PhpRedisConnection extends Connection implements ConnectionContract
  10. {
  11. use PacksPhpRedisValues;
  12. /**
  13. * The connection creation callback.
  14. *
  15. * @var callable
  16. */
  17. protected $connector;
  18. /**
  19. * The connection configuration array.
  20. *
  21. * @var array
  22. */
  23. protected $config;
  24. /**
  25. * Create a new PhpRedis connection.
  26. *
  27. * @param \Redis $client
  28. * @param callable|null $connector
  29. * @param array $config
  30. * @return void
  31. */
  32. public function __construct($client, ?callable $connector = null, array $config = [])
  33. {
  34. $this->client = $client;
  35. $this->config = $config;
  36. $this->connector = $connector;
  37. }
  38. /**
  39. * Returns the value of the given key.
  40. *
  41. * @param string $key
  42. * @return string|null
  43. */
  44. public function get($key)
  45. {
  46. $result = $this->command('get', [$key]);
  47. return $result !== false ? $result : null;
  48. }
  49. /**
  50. * Get the values of all the given keys.
  51. *
  52. * @param array $keys
  53. * @return array
  54. */
  55. public function mget(array $keys)
  56. {
  57. return array_map(function ($value) {
  58. return $value !== false ? $value : null;
  59. }, $this->command('mget', [$keys]));
  60. }
  61. /**
  62. * Set the string value in the argument as the value of the key.
  63. *
  64. * @param string $key
  65. * @param mixed $value
  66. * @param string|null $expireResolution
  67. * @param int|null $expireTTL
  68. * @param string|null $flag
  69. * @return bool
  70. */
  71. public function set($key, $value, $expireResolution = null, $expireTTL = null, $flag = null)
  72. {
  73. return $this->command('set', [
  74. $key,
  75. $value,
  76. $expireResolution ? [$flag, $expireResolution => $expireTTL] : null,
  77. ]);
  78. }
  79. /**
  80. * Set the given key if it doesn't exist.
  81. *
  82. * @param string $key
  83. * @param string $value
  84. * @return int
  85. */
  86. public function setnx($key, $value)
  87. {
  88. return (int) $this->command('setnx', [$key, $value]);
  89. }
  90. /**
  91. * Get the value of the given hash fields.
  92. *
  93. * @param string $key
  94. * @param mixed ...$dictionary
  95. * @return array
  96. */
  97. public function hmget($key, ...$dictionary)
  98. {
  99. if (count($dictionary) === 1) {
  100. $dictionary = $dictionary[0];
  101. }
  102. return array_values($this->command('hmget', [$key, $dictionary]));
  103. }
  104. /**
  105. * Set the given hash fields to their respective values.
  106. *
  107. * @param string $key
  108. * @param mixed ...$dictionary
  109. * @return int
  110. */
  111. public function hmset($key, ...$dictionary)
  112. {
  113. if (count($dictionary) === 1) {
  114. $dictionary = $dictionary[0];
  115. } else {
  116. $input = collect($dictionary);
  117. $dictionary = $input->nth(2)->combine($input->nth(2, 1))->toArray();
  118. }
  119. return $this->command('hmset', [$key, $dictionary]);
  120. }
  121. /**
  122. * Set the given hash field if it doesn't exist.
  123. *
  124. * @param string $hash
  125. * @param string $key
  126. * @param string $value
  127. * @return int
  128. */
  129. public function hsetnx($hash, $key, $value)
  130. {
  131. return (int) $this->command('hsetnx', [$hash, $key, $value]);
  132. }
  133. /**
  134. * Removes the first count occurrences of the value element from the list.
  135. *
  136. * @param string $key
  137. * @param int $count
  138. * @param mixed $value
  139. * @return int|false
  140. */
  141. public function lrem($key, $count, $value)
  142. {
  143. return $this->command('lrem', [$key, $value, $count]);
  144. }
  145. /**
  146. * Removes and returns the first element of the list stored at key.
  147. *
  148. * @param mixed ...$arguments
  149. * @return array|null
  150. */
  151. public function blpop(...$arguments)
  152. {
  153. $result = $this->command('blpop', $arguments);
  154. return empty($result) ? null : $result;
  155. }
  156. /**
  157. * Removes and returns the last element of the list stored at key.
  158. *
  159. * @param mixed ...$arguments
  160. * @return array|null
  161. */
  162. public function brpop(...$arguments)
  163. {
  164. $result = $this->command('brpop', $arguments);
  165. return empty($result) ? null : $result;
  166. }
  167. /**
  168. * Removes and returns a random element from the set value at key.
  169. *
  170. * @param string $key
  171. * @param int|null $count
  172. * @return mixed|false
  173. */
  174. public function spop($key, $count = 1)
  175. {
  176. return $this->command('spop', func_get_args());
  177. }
  178. /**
  179. * Add one or more members to a sorted set or update its score if it already exists.
  180. *
  181. * @param string $key
  182. * @param mixed ...$dictionary
  183. * @return int
  184. */
  185. public function zadd($key, ...$dictionary)
  186. {
  187. if (is_array(end($dictionary))) {
  188. foreach (array_pop($dictionary) as $member => $score) {
  189. $dictionary[] = $score;
  190. $dictionary[] = $member;
  191. }
  192. }
  193. $options = [];
  194. foreach (array_slice($dictionary, 0, 3) as $i => $value) {
  195. if (in_array($value, ['nx', 'xx', 'ch', 'incr', 'gt', 'lt', 'NX', 'XX', 'CH', 'INCR', 'GT', 'LT'], true)) {
  196. $options[] = $value;
  197. unset($dictionary[$i]);
  198. }
  199. }
  200. return $this->command('zadd', array_merge([$key], [$options], array_values($dictionary)));
  201. }
  202. /**
  203. * Return elements with score between $min and $max.
  204. *
  205. * @param string $key
  206. * @param mixed $min
  207. * @param mixed $max
  208. * @param array $options
  209. * @return array
  210. */
  211. public function zrangebyscore($key, $min, $max, $options = [])
  212. {
  213. if (isset($options['limit']) && ! array_is_list($options['limit'])) {
  214. $options['limit'] = [
  215. $options['limit']['offset'],
  216. $options['limit']['count'],
  217. ];
  218. }
  219. return $this->command('zRangeByScore', [$key, $min, $max, $options]);
  220. }
  221. /**
  222. * Return elements with score between $min and $max.
  223. *
  224. * @param string $key
  225. * @param mixed $min
  226. * @param mixed $max
  227. * @param array $options
  228. * @return array
  229. */
  230. public function zrevrangebyscore($key, $min, $max, $options = [])
  231. {
  232. if (isset($options['limit']) && ! array_is_list($options['limit'])) {
  233. $options['limit'] = [
  234. $options['limit']['offset'],
  235. $options['limit']['count'],
  236. ];
  237. }
  238. return $this->command('zRevRangeByScore', [$key, $min, $max, $options]);
  239. }
  240. /**
  241. * Find the intersection between sets and store in a new set.
  242. *
  243. * @param string $output
  244. * @param array $keys
  245. * @param array $options
  246. * @return int
  247. */
  248. public function zinterstore($output, $keys, $options = [])
  249. {
  250. return $this->command('zinterstore', [$output, $keys,
  251. $options['weights'] ?? null,
  252. $options['aggregate'] ?? 'sum',
  253. ]);
  254. }
  255. /**
  256. * Find the union between sets and store in a new set.
  257. *
  258. * @param string $output
  259. * @param array $keys
  260. * @param array $options
  261. * @return int
  262. */
  263. public function zunionstore($output, $keys, $options = [])
  264. {
  265. return $this->command('zunionstore', [$output, $keys,
  266. $options['weights'] ?? null,
  267. $options['aggregate'] ?? 'sum',
  268. ]);
  269. }
  270. /**
  271. * Scans all keys based on options.
  272. *
  273. * @param mixed $cursor
  274. * @param array $options
  275. * @return mixed
  276. */
  277. public function scan($cursor, $options = [])
  278. {
  279. $result = $this->client->scan($cursor,
  280. $options['match'] ?? '*',
  281. $options['count'] ?? 10
  282. );
  283. if ($result === false) {
  284. $result = [];
  285. }
  286. return $cursor === 0 && empty($result) ? false : [$cursor, $result];
  287. }
  288. /**
  289. * Scans the given set for all values based on options.
  290. *
  291. * @param string $key
  292. * @param mixed $cursor
  293. * @param array $options
  294. * @return mixed
  295. */
  296. public function zscan($key, $cursor, $options = [])
  297. {
  298. $result = $this->client->zscan($key, $cursor,
  299. $options['match'] ?? '*',
  300. $options['count'] ?? 10
  301. );
  302. if ($result === false) {
  303. $result = [];
  304. }
  305. return $cursor === 0 && empty($result) ? false : [$cursor, $result];
  306. }
  307. /**
  308. * Scans the given hash for all values based on options.
  309. *
  310. * @param string $key
  311. * @param mixed $cursor
  312. * @param array $options
  313. * @return mixed
  314. */
  315. public function hscan($key, $cursor, $options = [])
  316. {
  317. $result = $this->client->hscan($key, $cursor,
  318. $options['match'] ?? '*',
  319. $options['count'] ?? 10
  320. );
  321. if ($result === false) {
  322. $result = [];
  323. }
  324. return $cursor === 0 && empty($result) ? false : [$cursor, $result];
  325. }
  326. /**
  327. * Scans the given set for all values based on options.
  328. *
  329. * @param string $key
  330. * @param mixed $cursor
  331. * @param array $options
  332. * @return mixed
  333. */
  334. public function sscan($key, $cursor, $options = [])
  335. {
  336. $result = $this->client->sscan($key, $cursor,
  337. $options['match'] ?? '*',
  338. $options['count'] ?? 10
  339. );
  340. if ($result === false) {
  341. $result = [];
  342. }
  343. return $cursor === 0 && empty($result) ? false : [$cursor, $result];
  344. }
  345. /**
  346. * Execute commands in a pipeline.
  347. *
  348. * @param callable|null $callback
  349. * @return \Redis|array
  350. */
  351. public function pipeline(?callable $callback = null)
  352. {
  353. $pipeline = $this->client()->pipeline();
  354. return is_null($callback)
  355. ? $pipeline
  356. : tap($pipeline, $callback)->exec();
  357. }
  358. /**
  359. * Execute commands in a transaction.
  360. *
  361. * @param callable|null $callback
  362. * @return \Redis|array
  363. */
  364. public function transaction(?callable $callback = null)
  365. {
  366. $transaction = $this->client()->multi();
  367. return is_null($callback)
  368. ? $transaction
  369. : tap($transaction, $callback)->exec();
  370. }
  371. /**
  372. * Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself.
  373. *
  374. * @param string $script
  375. * @param int $numkeys
  376. * @param mixed ...$arguments
  377. * @return mixed
  378. */
  379. public function evalsha($script, $numkeys, ...$arguments)
  380. {
  381. return $this->command('evalsha', [
  382. $this->script('load', $script), $arguments, $numkeys,
  383. ]);
  384. }
  385. /**
  386. * Evaluate a script and return its result.
  387. *
  388. * @param string $script
  389. * @param int $numberOfKeys
  390. * @param mixed ...$arguments
  391. * @return mixed
  392. */
  393. public function eval($script, $numberOfKeys, ...$arguments)
  394. {
  395. return $this->command('eval', [$script, $arguments, $numberOfKeys]);
  396. }
  397. /**
  398. * Subscribe to a set of given channels for messages.
  399. *
  400. * @param array|string $channels
  401. * @param \Closure $callback
  402. * @return void
  403. */
  404. public function subscribe($channels, Closure $callback)
  405. {
  406. $this->client->subscribe((array) $channels, function ($redis, $channel, $message) use ($callback) {
  407. $callback($message, $channel);
  408. });
  409. }
  410. /**
  411. * Subscribe to a set of given channels with wildcards.
  412. *
  413. * @param array|string $channels
  414. * @param \Closure $callback
  415. * @return void
  416. */
  417. public function psubscribe($channels, Closure $callback)
  418. {
  419. $this->client->psubscribe((array) $channels, function ($redis, $pattern, $channel, $message) use ($callback) {
  420. $callback($message, $channel);
  421. });
  422. }
  423. /**
  424. * Subscribe to a set of given channels for messages.
  425. *
  426. * @param array|string $channels
  427. * @param \Closure $callback
  428. * @param string $method
  429. * @return void
  430. */
  431. public function createSubscription($channels, Closure $callback, $method = 'subscribe')
  432. {
  433. //
  434. }
  435. /**
  436. * Flush the selected Redis database.
  437. *
  438. * @return mixed
  439. */
  440. public function flushdb()
  441. {
  442. $arguments = func_get_args();
  443. if (strtoupper((string) ($arguments[0] ?? null)) === 'ASYNC') {
  444. return $this->command('flushdb', [true]);
  445. }
  446. return $this->command('flushdb');
  447. }
  448. /**
  449. * Execute a raw command.
  450. *
  451. * @param array $parameters
  452. * @return mixed
  453. */
  454. public function executeRaw(array $parameters)
  455. {
  456. return $this->command('rawCommand', $parameters);
  457. }
  458. /**
  459. * Run a command against the Redis database.
  460. *
  461. * @param string $method
  462. * @param array $parameters
  463. * @return mixed
  464. *
  465. * @throws \RedisException
  466. */
  467. public function command($method, array $parameters = [])
  468. {
  469. try {
  470. return parent::command($method, $parameters);
  471. } catch (RedisException $e) {
  472. foreach (['went away', 'socket', 'read error on connection', 'Connection lost'] as $errorMessage) {
  473. if (str_contains($e->getMessage(), $errorMessage)) {
  474. $this->client = $this->connector ? call_user_func($this->connector) : $this->client;
  475. break;
  476. }
  477. }
  478. throw $e;
  479. }
  480. }
  481. /**
  482. * Disconnects from the Redis instance.
  483. *
  484. * @return void
  485. */
  486. public function disconnect()
  487. {
  488. $this->client->close();
  489. }
  490. /**
  491. * Pass other method calls down to the underlying client.
  492. *
  493. * @param string $method
  494. * @param array $parameters
  495. * @return mixed
  496. */
  497. public function __call($method, $parameters)
  498. {
  499. return parent::__call(strtolower($method), $parameters);
  500. }
  501. }