Home  >  Article  >  Backend Development  >  In-depth analysis of Session server configuration guide and usage experience_PHP tutorial

In-depth analysis of Session server configuration guide and usage experience_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:05:44903browse

1. Summary
All Web programs will use Session to save data. Using an independent Session server can solve the Session sharing problem in load balancing scenarios. This article introduces the establishment of a .NET platform Several methods of Session server, and introduces various experiences and techniques when using Session.

2. About Session, SessionID and Cookies
Session The data is stored on the server side, but each client needs to save a SessionID. The SessionID is stored in Cookies and expires when the browser is closed.

The SessionID will be included in the HTTP request sent to the server. The server side will SessionID gets the session information of this user.
Many junior developers don’t know the relationship between SessionID and Cookies, so they often think that there is no connection between the two. This is incorrect. It is precisely because SessionID is stored in Cookies, so in our When saving cookies, be sure not to create SessionID objects due to the size and number of cookies. In our program, there are special treatments for SessionID cookies:

Copy Code The code is as follows:

///
/// Write cookie.
///

/// string CookieName = GetType().ToString();
HttpCookie SessionCookie = null;
//Back up SessionId.
if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] ! = null)
{
string SesssionId = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value.ToString();
SessionCookie = new HttpCookie("ASP .NET_SessionId");
SessionCookie.Value = SesssionId;
} //Omit the middle code part. Only keep the logic of backing up SessionID and retrieving SessionID //If the total number of cookies exceeds 20, repeat Write ASP.NET_SessionId, in case Session is lost.
if (HttpContext.Current.Request.Cookies.Count > 20 && SessionCookie != null)
                                                                            > Httpcontext.current.Response.cookies.remove ("asp.net_sessionid"); 🎜>} Return true;
}


三.搭建Session服务器的几种方式
将Session保存在独立的服务器中可以实现在多台Web服务器之间共享Session.虽然我们也可以自己开发Session存储系统, 但是使用ASP.NET自带的存储机制将更加便捷.
.NET提供了5种保存Seission的方式:

方式名称

存储方式 性能

Off

设置为不使用Session功能

InProc

设置为将Session存储在进程内,就是ASP中的存储方式,这是默认值。

性能最高

StateServer

设置为将Session存储在独立的状态服务中。通常是aspnet_state.exe进程.

性能损失10-15%

SQLServer

设置将Session存储在SQL Server中。

性能损失10-20%

Customer

自定制的存储方案

由实现方式确定

我们可以在Web.Config中配置程序使用的Session存储方式.默认情况下是InProc, 即保存在IIS进程中. 关于Off, InProc和Customer本文不做讲解. 相关文章大家都可以在网上搜索到.
下面主要讲解 StateServer 和 SQLServer 的应用.

四.使用 StateServer 模式搭建Session服务器
(1)服务器端配置
1.启动 Asp.net State service服务.(这个服务默认的状态为手动.修改为自动并启动.)
2.修改注册表: [HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\aspnet_state\Parameters]
设置 AllowRemoteConnection = 1 , 设置 Port = 42424 (十进制,默认即为42424)
Port是服务的端口号
AllowRemoteConnection 表示是否允许其他机器连接,0为仅能本机使用,1为可以供其他机器使用.

(2)客户端设置
在Web应用程序的Web.Config中, 我们需要修改 / 节点.如果没有
没有则添加(默认使用的是InProc方式)

复制代码 代码如下:

mode="StateServer"
stateConnectionString="tcpip=服务器ip:42424"
cookieless="false"
timeout="60"/>

上面的参数我们可以根据需要修改.

五.使用SqlServer模式搭建Session服务器
(1)服务器端配置
使用SqlServer模式搭建Session服务器端有两种方式. ASP.NET 1.0和1.1版本请使用方式a, 2.0即以上版本请使用方式b.

a.使用SQL文件创建Session数据库
在ASP.NET 1.0和1.1 版本中, 只能使用这种方式.对于2.0及其以上版本,请使用aspnet_regsql.exe工具.(当然此方法也通用2.0版本)
.net提供了数据库安装脚本,可以在机器的windows文件夹中找到:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ InstallSqlState.sql
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ InstallSqlStateTemplate.sql
根据ASP.NET的版本不同, 需要使用不同的SQL脚本. ASP.NET主要有1.1和2.0两个版本,可以在不同的版本文件夹找到这两个SQL.
InstallSqlState.sql 是创建默认名称的数据库"[ASPState]".此SQL可以直接运行.
InstallSqlStateTemplate.sql 可以使用自己指定的数据库保存数据.此SQL需要自己修改后运行, 打开SQL文件将其中 [DatabaseNamePlaceHolder] 替换为自己指定的数据库名称.
执行installsqlstate.sql时不需要指定数据库,可以在任意数据库上执行.此SQL会自己创建新的数据库

b. 使用aspnet_regsql.exe工具
ASP.NET 2.0版本后微软提供了aspnet_regsql.exe工具可以方便的配置Session数据库.该工具位于 Web 服务器上的"系统根目录\Microsoft.NET\Framework\版本号"文件夹中.
使用举例:
aspnet_regsql.exe -S . -U sa -P 123456 -ssadd -sstype p
-S参数:
表示数据库实例名称. 可以用"."表示本机.
-U和-P参数:
表示用户名和密码.
-E参数:
可以再-U –P 与 -E中选择一组. –E表示以当前系统用户通过windows身份验证登录数据库, -U -P则是使用SqlServer用户登录数据库.
-ssadd / –ssremove 参数:
-ssadd表示是添加Session数据库, -ssremove表示移除Session数据库.
sstype 参数:

选项

说明

t

将会话数据存储到 SQL Server tempdb 数据库中。这是默认设置。如果将会话数据存储到 tempdb 数据库中,则在重新启动 SQL Server 时将丢失会话数据。

p

将会话数据存储到 ASPState 数据库中,而不是存储到 tempdb 数据库中。

c

将会话数据存储到自定义数据库中。如果指定 c 选项,则还必须使用 -d 选项包括自定义数据库的名称。

(2)Session client settings
This room also requires the web application to modify the node in Web.Config. If the default database (ASPState library) is used, then The configuration is as follows:

Copy the code The code is as follows:

mode="SQLServer"
sqlConnectionString ="server=192.168.9.151; uid=sa; pwd=123456;"
/>

If a custom database name is used, you also need to formulate the allowCustomSqlDatabase attribute and add it to the database Specify the database in the connection string:
Copy the code The code is as follows:

mode="SQLServer"
allowCustomSqlDatabase="true"
sqlConnectionString="server=192.168.9.151; DataBase=MyAspState;uid=sa; pwd=123456;"
/>

6. Summary of usage experience and skills
The following is a summary of various experiences and skills of SessionID, Session_End time, StatServer mode and SqlServer mode.
(1) StateServer mode :
1. In the web farm, please confirm that there is the same
on all web servers. 2. The objects to be saved in the Session are serializable.
3. In order to maintain session state on different web servers in the web farm, the website application path (such as LMW3SVC2) in IIS Metabase should be consistent on all servers (case sensitive).
4. ASP.NET handles Session through the HttpModuel module configured in Machine.Config. In the Config folder under the .NET installation directory, view Web.Config (version 1.1 is in Machine.Config):
Copy code The code is as follows:

                                                                        SessionState.SessionStateModule"/>
...                                                                                                                                                                                                                                                                                  In SqlServer mode, you can enjoy the high performance and security of SqlServer. Although the storage efficiency will decrease.
6. The MachineKey of all machines needs to be the same. Configure in Machine.Config:


Copy code

The code is as follows:
validationKey="1234567890123456789012345678901234567890AAAAAAAAA" decryptionKey="12345678 9012345678901234567890123456789012345678"
validation="SHA1"
decryption="Auto"
/>



(2)SqlServer mode:

1. The object to be saved in the Session is serializable ized.
2. If the default database is used, the user of the database link string in the client configuration file needs to have dbowner permissions for the ASPState and tempdb libraries.
3. In SQLServer mode, session Expiration is done by SQL Agent using a registration task. Make sure SQL Agent is running. Otherwise, the expired Session data cannot be cleaned, which will cause the database data to keep increasing. 4. If you use SqlServer mode, the ASP.NET application path for each server in the Web farm must be the same. Synchronize the application path of the Web site in the IIS configuration database for all Web servers in the Web farm. The case must be the same because the application path to the Web site is case-sensitive.
5. The MachineKey of all machines needs to be the same. Configure in Machine.Config:



Copy the code

The code is as follows:
validationKey="1234567890123456789012345678901234567890AAAAAAAAA" decryptionKey="1234567890123456789012345678901234 5678"
validation="SHA1"
decryption="Auto"
/>


(3)Session:
1. Sessions cannot be shared between ASP.NET and ASP directly through the Session server. Please use the solution provided by Microsoft:
http:// msdn.microsoft.com/zh-cn/library/aa479313.aspx
2. Session cannot be shared between different applications or different virtual directories of a website
3. Session expiration time is a sliding time.
4. Session stores the value type that comes with .NET for the best performance. Storing objects will reduce performance.
(4)SessionID:
1.SessionID can also be saved in the URL , just set the Cookiesless attribute of the System.Web/sessionState node in the Web.Config file:
Copy the code The code is as follows:

cookieless="UseUri"
/>

2. Generally, the SessionID remains unchanged after the Session times out or is deleted. This is because the Session ID will remain unchanged on the server after it expires. The data is cleared on the client, but the SessionID is saved on the user's browser, so as long as the browser is not closed, the SessionID in the HTTP header remains unchanged.
3. After closing the browser and accessing again, the SessionID will be different.
4. Every time an IE6 window is opened, the SessionID is different. In IE6, the Session of the two windows cannot be shared.
5. The SessionID of the FireFox tab page and the new FireFox window are the same, but the SessionID of the FF window and tab page cannot be shared. Share.
6. For pages containing FrameSet, for example:
Copy the code The code is as follows:







If the suffix is ​​.htm and the .htm file is not handed over to ASP.NET's ISAPI for processing, then based on the server speed A different SessionID is generated in each Frame page, and the same SessionID will be equal to the last SessionID after refreshing.
The solution is to change the .htm suffix to .aspx, or hand the .htm file to the ISAPI of ASP.NET for processing.
(5)Session_End event:
1. Session_End is only available in InProc mode
2. Close the browser, Session_End will not be triggered. HTTP is a stateless protocol, and the server has no way of knowing whether your browser has been closed.
3. Session_End will only be triggered when the Session expires or calls Session.Abandon. Session.Clear() only clears the data, but does not delete the session.
4. Session_End is triggered by a background thread and runs using the worker process account. Therefore, the program will not notify errors that occur.
5. Permission issues must be considered when accessing the database in Session_End. Session_End is used to run the worker process ( aspnet_wp.exe), this account can be specified in machine.config. Therefore, in Session_End, if integrity security is used to connect to SQL, it will use the worker process account identity to connect, which may cause login failure.
6. Because Session_End is initiated by an independent thread, it cannot be used in Session_End HttpContext object (Request, Response, Server and other objects are all in HttpContext), that is, methods such as Response.Redirect and Server.Transfer cannot be used.

7. Summary
I have used the SqlServer mode to implement session sharing for multiple servers in the company. Restarting the server will not cause the user reservation process to restart (booking The Session required for the process will not be lost). I hope this article will be helpful to those who build specific Session servers.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327659.htmlTechArticle1. Summary All web programs will use Session to save data. Using an independent Session server can solve the problem in load balancing scenarios Session sharing problem. This article introduces the establishment of Ses under the .NET platform...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn