Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
redisconnectionconfigurator.php
1<?php
2
4
7
9{
11 protected $config;
13 protected $servers = [];
14
15 public function __construct($config)
16 {
17 if (!extension_loaded('redis'))
18 {
19 throw new NotSupportedException('redis extension is not loaded.');
20 }
21
22 $this->config = $config;
23
24 $this->addServers($this->getConfig());
25 }
26
27 protected function addServers($config)
28 {
29 $servers = $config['servers'] ?? [];
30
31 if (empty($servers) && isset($config['host'], $config['port']))
32 {
33 array_unshift($servers, [
34 'host' => $config['host'],
35 'port' => $config['port'],
36 ]);
37 }
38
39 foreach ($servers as $server)
40 {
41 $this->servers[] = [
42 'host' => $server['host'] ?? 'localhost',
43 'port' => $server['port'] ?? '6379',
44 ];
45 }
46
47 return $this;
48 }
49
50 public function getConfig()
51 {
52 return $this->config;
53 }
54
58 protected function configureConnection($connection): void
59 {
60 $config = $this->getConfig();
61
62 if ($connection instanceof \Redis)
63 {
64 $connection->setOption(\Redis::OPT_SERIALIZER, $config['serializer'] ?? \Redis::SERIALIZER_IGBINARY);
65 }
66 elseif ($connection instanceof \RedisCluster)
67 {
68 $connection->setOption(
69 \RedisCluster::OPT_SERIALIZER,
70 $config['serializer'] ?? \RedisCluster::SERIALIZER_IGBINARY
71 );
72
73 if (count($this->servers) > 1)
74 {
75 $connection->setOption(
76 \RedisCluster::OPT_SLAVE_FAILOVER,
77 $config['failover'] ?? \RedisCluster::FAILOVER_NONE
78 );
79 }
80 }
81 }
82
83 public function createConnection()
84 {
85 $config = $this->getConfig();
86 if (!$this->servers)
87 {
88 throw new NotSupportedException('Empty server list to redis connection.');
89 }
90
91 if (count($this->servers) === 1)
92 {
93 ['host' => $host, 'port' => $port] = $this->servers[0];
94 $connection = new \Redis();
95
96 if ($config['persistent'])
97 {
98 $result = $connection->pconnect($host, $port);
99 }
100 else
101 {
102 $result = $connection->connect($host, $port);
103 }
104 }
105 else
106 {
107 $connections = [];
108 foreach ($this->servers as $server)
109 {
110 $connections[] = $server['host'] . ':' . $server['port'];
111 }
112
113 $connection = new \RedisCluster(
114 null,
115 $connections,
116 $config['timeout'] ?? null,
117 $config['readTimeout'] ?? null,
118 $config['persistent'] ?? true
119 );
120 $result = true;
121 }
122
123 if ($result)
124 {
125 $this->configureConnection($connection);
126 }
127 else
128 {
129 $error = error_get_last();
130 if (isset($error["type"]) && $error["type"] === E_WARNING)
131 {
132 $exception = new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']);
133 $application = Application::getInstance();
134 $exceptionHandler = $application->getExceptionHandler();
135 $exceptionHandler->writeToLog($exception);
136 }
137 }
138
139 return $result? $connection : null;
140 }
141}