php利用redis实现session共享
php利用redis实现session共享
单机时候,直接用file来存放session即可,但是多实例部署的时候,如韵筹官网,因为多实例负载均衡的原因,session无法使用file共享,导致存入在session中的验证码变来边去,登录遇到困难,需要解决多实例session共享问题,说来也简单,直接利用redis共享即可。当然也能写入到数据库中共享。
files
写入到文件
[Session]
; Handler used to store/retrieve data.
; http://php.net/session.save-handler
session.save_handler = files
redis
参见phpredis扩展说明。
需要在php.ini中配置session.save_handler和session.save_path,来告诉phpredis扩展,session存储的位置。
session.save_handler = redis
session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2&read_timeout=2.5"
session.save_path也可以简单的写成host:port的形式,如果需要使用参数,则必须添加tcp://协议的前缀。
参数:
- weight (整数),权重
- timeout (float) ,超时
- persistent (integer, should be 1 or 0): defines if a persistent connection should be used.
- prefix (string, defaults to “PHPREDIS_SESSION:”): used as a prefix to the Redis key in which the session is stored. The key is composed of the prefix followed by the session ID.
- auth (string, empty by default): used to authenticate with the server prior to sending commands.
- database (integer):选择不同的数据库。
memcache
参见文章https://www.cnblogs.com/fukai-blog/p/6860151.html
session.save_handler = memcache
session.save_path = "tcp://127.0.0.1:11211"
设置方法有三种。
方法I: 在 php.ini 中全局设置
session.save_handler = memcache
session.save_path = “tcp://127.0.0.1:11211”方法II: 某个目录下的 .htaccess :
php_value session.save_handler “memcache”
php_value session.save_path “tcp://127.0.0.1:11211”方法III: 再或者在某个一个应用中:
ini_set(“session.save_handler”, “memcache”);
ini_set(“session.save_path”, “tcp://127.0.0.1:11211”);
mysql
可以使用session_set_save_handler来定制使用mysql,而官方的手册里面,有例子,这里略。