RedisClusterSessionHandler.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. declare(strict_types=1);
  15. namespace Workerman\Protocols\Http\Session;
  16. use Redis;
  17. use RedisCluster;
  18. use RedisClusterException;
  19. use RedisException;
  20. class RedisClusterSessionHandler extends RedisSessionHandler
  21. {
  22. /**
  23. * @param $config
  24. * @throws RedisClusterException
  25. * @throws RedisException
  26. */
  27. public function __construct($config)
  28. {
  29. $timeout = $config['timeout'] ?? 2;
  30. $readTimeout = $config['read_timeout'] ?? $timeout;
  31. $persistent = $config['persistent'] ?? false;
  32. $auth = $config['auth'] ?? '';
  33. $args = [null, $config['host'], $timeout, $readTimeout, $persistent];
  34. if ($auth) {
  35. $args[] = $auth;
  36. }
  37. $this->redis = new RedisCluster(...$args);
  38. if (empty($config['prefix'])) {
  39. $config['prefix'] = 'redis_session_';
  40. }
  41. $this->redis->setOption(Redis::OPT_PREFIX, $config['prefix']);
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function read(string $sessionId): string
  47. {
  48. return $this->redis->get($sessionId);
  49. }
  50. }