PhpRedisConnection.php 14 KB

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