PHP使用Redis實(shí)現(xiàn)Session共享的實(shí)現(xiàn)示例
前言
小型web服務(wù), session數(shù)據(jù)基本是保存在本地(更多是本地磁盤文件), 但是當(dāng)部署多臺(tái)服務(wù), 且需要共享session, 確保每個(gè)服務(wù)都能共享到同一份session數(shù)據(jù).
redis 數(shù)據(jù)存儲(chǔ)在內(nèi)存中, 性能好, 配合持久化可確保數(shù)據(jù)完整.
設(shè)計(jì)方案
1. 通過(guò)php自身session配置實(shí)現(xiàn)
# 使用 redis 作為存儲(chǔ)方案 session.save_handler = redis session.save_path = "tcp://127.0.0.1:6379" # 若設(shè)置了連接密碼, 則使用如下 session.save_path = "tcp://127.0.0.1:6379?auth=密碼"
測(cè)試代碼
<?php
ini_set("session.save_handler", "redis");
ini_set("session.save_path", "tcp://127.0.0.1:6379");
session_start();
echo "<pre>";
$_SESSION['usertest'.rand(1,5)]=1;
var_dump($_SESSION);
echo "</pre>";
輸出 ↓
array(2) {
["usertest1"]=>
int(88)
["usertest3"]=>
int(1)
}
usertest1|i:1;usertest3|i:1;
評(píng)價(jià)
- 優(yōu)點(diǎn): 實(shí)現(xiàn)簡(jiǎn)單, 無(wú)需修改php代碼
- 缺點(diǎn): 配置不支持多樣化, 只能應(yīng)用于簡(jiǎn)單場(chǎng)景
2. 設(shè)置用戶自定義會(huì)話存儲(chǔ)函數(shù)
通過(guò) session_set_save_handler() 函數(shù)設(shè)置用戶自定義會(huì)話函數(shù).
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
在配置完會(huì)話存儲(chǔ)函數(shù)后, 再執(zhí)行 session_start() 即可.
具體代碼略, 以下提供一份 Memcached 的(來(lái)自Symfony框架代碼):
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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 <drak@zikula.org>
*/
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;
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ThinkPHP3.2.3數(shù)據(jù)庫(kù)設(shè)置新特性
前篇文章,我們總結(jié)了下ThinkPHP3.2中所產(chǎn)生的新變化,本文我們來(lái)詳細(xì)看下關(guān)于數(shù)據(jù)庫(kù)這塊有哪些新特性,非常細(xì)致,有需要的小伙伴參考下。2015-03-03
php模擬ping命令(php exec函數(shù)的使用方法)
使用php模擬我們常用的DOS命令ping命令的方法,這中間用到了exec函數(shù)并做函數(shù)解釋,還有相關(guān)函數(shù)system的使用。2013-10-10
thinkPHP模板中for循環(huán)與switch語(yǔ)句用法示例
這篇文章主要介紹了thinkPHP模板中for循環(huán)與switch語(yǔ)句用法,結(jié)合實(shí)例形式分析了for循環(huán)與switch語(yǔ)句的具體功能、定義與具體使用技巧,需要的朋友可以參考下2016-11-11
php 使用mpdf實(shí)現(xiàn)指定字段配置字體樣式的方法
前兩天在做一個(gè)pdf導(dǎo)出功能,使用的插件是kartik-v/yii2-mpdf,此插件使用的是mpdf。接下來(lái)通過(guò)本文給大家介紹php 使用mpdf實(shí)現(xiàn)指定字段配置字體樣式的方法,需要的朋友可以參考下2019-07-07
tp5修改(實(shí)現(xiàn)即點(diǎn)即改)
今天小編就為大家分享一篇tp5修改(實(shí)現(xiàn)即點(diǎn)即改),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-10-10
完美的2個(gè)php檢測(cè)字符串是否是utf-8編碼函數(shù)分享
這篇文章主要介紹了完美的2個(gè)php檢測(cè)字符串是否是utf-8編碼函數(shù)分享,一個(gè)比較強(qiáng)大、一個(gè)比較簡(jiǎn)潔,需要的朋友可以參考下2014-07-07
Yii 訪問(wèn) Gii(腳手架)時(shí)出現(xiàn) 403 錯(cuò)誤
這篇文章主要介紹了Yii 訪問(wèn) Gii(腳手架)時(shí)出現(xiàn) 403 錯(cuò)誤的解決方法的相關(guān)資料,需要的朋友可以參考下2018-06-06
php使用curl發(fā)送json格式數(shù)據(jù)實(shí)例
這篇文章主要介紹了php使用curl發(fā)送json格式數(shù)據(jù)的實(shí)例,大家參考使用吧2013-12-12

