PHP默认的会话处理器是session.save_handler = files(即文件)。如果同一个客户端同时向服务器发送多个请求,其中有一个php脚本中使用了session,并且这个php脚本中使用了长轮询,就会导致session文件阻塞,直到这个长轮询的php脚本返回数据后其他请求才能够执行,在此过程中其他请求都处于等待阶段,这样严重影响了网站的速度。因为对于每个请求,PHP执行session_start(),就会取得文件独占锁,只有在该请求处理结束后,才会释放独占锁。这样,同时多个请求就会引起阻塞。
由于我们公司是游戏公司,在开发一款游戏时使用了长轮询,更巧的是在这个长轮询的页面中所加载的配置文件中开启了session,以便项目中使用session,但是其实在这个php页面中并没有使用session。正因如此才发生了上述的情况。当时在解决此问题时真是费了一番周折,多次调试代码无果,最后想到了session锁的问题,于是所session_start()注释掉问题迎刃而解。在此项目中若没有使用到session则可以将session_start()去掉,若使用了session则如何解决呢?具体解决办法如下:
其实,在我们php中还有一个函数session_write_close()函数,那这个函数究竟干嘛用的呢?官方解释如下:
End the current session and store session data.
Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.
其大概意思就是说我们在一般情况下使用session存储数据时不需要调用session_write_close()函数,但是一旦session数据被锁定我们只能使用session_write_close()函数来结束当前的session并存储session数据。
由于我们公司是游戏公司,在开发一款游戏时使用了长轮询,更巧的是在这个长轮询的页面中所加载的配置文件中开启了session,以便项目中使用session,但是其实在这个php页面中并没有使用session。正因如此才发生了上述的情况。当时在解决此问题时真是费了一番周折,多次调试代码无果,最后想到了session锁的问题,于是所session_start()注释掉问题迎刃而解。在此项目中若没有使用到session则可以将session_start()去掉,若使用了session则如何解决呢?具体解决办法如下:
其实,在我们php中还有一个函数session_write_close()函数,那这个函数究竟干嘛用的呢?官方解释如下:
End the current session and store session data.
Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.
其大概意思就是说我们在一般情况下使用session存储数据时不需要调用session_write_close()函数,但是一旦session数据被锁定我们只能使用session_write_close()函数来结束当前的session并存储session数据。