Последнее изменение: 16:06:36, 10 мая 2019
Для небольших веб-служб данные сеанса в основном хранятся локально (больше файлов на локальном диске), но когда развернуто несколько служб и требуется общий доступ к сеансам, убедитесь, что каждая служба может совместно использовать одни и те же данные сеанса
Данные Redis хранятся в памяти с хорошей производительностью. При постоянстве целостность данных может быть обеспечена
1. Через собственную конфигурацию сеанса PHP
#Using redis as a storage solution session.save_handler = redis session.save_path = "tcp://127.0.0.1:6379" #If the connection password is set, use the following Session.save_path = "TCP: // 127.0.0.1:6379? Auth = password"
Тестовый код
Выход выход
array(2) {
["usertest1"]=>
int(88)
["usertest3"]=>
int(1)
}
usertest1|i:1;usertest3|i:1;оценивать
- Преимущество: Простая реализация, нет необходимости изменять PHP-код
- Недостатки: Конфигурация не поддерживает диверсификацию и может применяться только к простым сценариям
2. Установите определяемую пользователем функцию хранения сеансов
Установите определяемую пользователем функцию сеанса с помощью функции обработчика сохранения набора сеансов()
session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid [, callable $validate_sid [, callable $update_timestamp ]]] ) : bool
# >= php5.4
session_set_save_handler ( object $sessionhandler [, bool $register_shutdown = TRUE ] ) : boolПосле настройки функции хранения сеанса выполните session_start() Да.
Конкретный код опущен, и копия предоставлена ниже Memcached Из кода платформы symfony:
[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** * MemcacheSessionHandler. * * @author Drak <[email protected]> */ class MemcacheSessionHandler implements \SessionHandlerInterface { /** * @var \Memcache Memcache driver. */ private $memcache; /** * @var int Time to live in seconds */ private $ttl; /** * @var string Key prefix for shared environments. */ private $prefix; /** * Constructor. * * List of available options: * * prefix: The prefix to use for the memcache keys in order to avoid collision * * expiretime: The time to live in seconds * * @param \Memcache $memcache A \Memcache instance * @param array $options An associative array of Memcache options * * @throws \InvalidArgumentException When unsupported options are passed */ public function __construct(\Memcache $memcache, array $options = array()) { if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) { throw new \InvalidArgumentException(sprintf( 'The following options are not supported "%s"', implode(', ', $diff) )); } $this->memcache = $memcache; $this->ttl = isset($options['expiretime']) ? (int) $options['expiretime'] : 86400; $this->prefix = isset($options['prefix']) ? $options['prefix'] : 'sf2s'; } /** * {@inheritdoc} */ public function open($savePath, $sessionName) { return true; } /** * {@inheritdoc} */ public function close() { return $this->memcache->close(); } /** * {@inheritdoc} */ public function read($sessionId) { return $this->memcache->get($this->prefix.$sessionId) ?: ''; } /** * {@inheritdoc} */ public function write($sessionId, $data) { return $this->memcache->set($this->prefix.$sessionId, $data, 0, time() + $this->ttl); } /** * {@inheritdoc} */ public function destroy($sessionId) { return $this->memcache->delete($this->prefix.$sessionId); } /** * {@inheritdoc} */ public function gc($maxlifetime) { // not required here because memcache will auto expire the records anyhow. return true; } /** * Return a Memcache instance * * @return \Memcache */ protected function getMemcache() { return $this->memcache; } }