Session Server Configuration Guide and in-depth analysis of usage experience _php tips

Source: Internet
Author: User
Tags httpcontext sessions sha1 versions metabase
I. Summary
All Web programs use session to save data. Using a separate session server solves the session sharing problem in the load balancing scenario. This article describes several ways to establish a session server under the. NET Platform, and introduces the various experiences and techniques in using session.

Two. About Session,sessionid and cookies
Session data is saved on the server side, but each client needs to save a SessionID, SessionID is stored in cookies and expires when the browser is closed.

A SessionID is included in the HTTP request sent to the server, and the server side obtains the session information for this user based on SessionID.
Many junior developers do not know the relationship between SessionID and cookies, so they often think they are not connected. This is not true. It is because SessionID is stored in cookies that when we save cookies, we must be careful not to cause the SessionID object because of the size and number of cookies. In our program, there are special treatments for SessionID cookies:
Copy Code code as follows:

<summary>
Write cookies.
</summary>
<param name= "Day" ></param>
<returns></returns>
public bool Setcookie (int day)
{
String cookiename = GetType (). ToString ();
HttpCookie Sessioncookie = null;
Make a backup of the 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 section of the code. Only keep backup SessionID and retrieve SessionID logic
If the total number of cookies exceeds 20, rewrite Asp.net_sessionid to prevent session loss.
if (HttpContext.Current.Request.Cookies.Count > && sessioncookie!= null)
{
if (Sessioncookie.value!= string. Empty)
{
HttpContext.Current.Response.Cookies.Remove ("Asp.net_sessionid");
HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Sessioncookie);
}
}
return true;
}

Three. Several ways to build session server
Saving sessions in a separate server enables you to share sessions across multiple Web servers. Although we can also develop the session storage system ourselves, it is more convenient to use the ASP.net storage mechanism.
. NET provides 5 ways to save Seission:

Way Name

Storage mode Performance

Off

Set to do not use the session feature

No

InProc

Set to store session in-process, which is the storage mode in ASP, which is the default value.

Highest performance

StateServer

Set to store the session in a separate state service. Usually the aspnet_state.exe process.

Performance Loss 10-15%

Sql server

Sets the session to be stored in SQL Server.

Performance Loss 10-20%

Customer

Self-customizing storage scenarios

Determined by the implementation method

We can configure the session storage method used by the program in Web.config. By default, it is InProc, which is saved in the IIS process. About off, InProc and customer this article does not explain. Related articles can be found on the Internet.
The following are the main explanations for StateServer and SQL Server applications.

Four. Use StateServer mode to build session server
(1) server-side configuration
1. Start asp.net State service. (The default state for this service is manual. Modify to Automatic and start.)
2. Modify the Registration form: [Hkey_local_machine\system\controlset001\services\aspnet_state\parameters]
Set allowremoteconnection = 1, set Port = 42424 (decimal, default to 42424)
Port is the port number of the service
Allowremoteconnection Indicates whether other machines are allowed to connect, 0 for only local use, and 1 for other machines to use.

(2) Client settings
In the web.config of the Web application, we need to modify the <configuration>/<system.web> <sessionState> node. If not
Not added (default is InProc method)

Copy Code code as follows:

<sessionstate
Mode= "StateServer"
stateconnectionstring= "tcpip= Server ip:42424"
Cookieless= "false"
Timeout= "/>"

The above parameters can be modified according to the need.

Five. Use SQL Server mode to build the session servers
(1) server-side configuration
There are two ways to build the session server side using SQL Server mode. ASP.net versions 1.0 and 1.1 please use mode A, 2.0 is the above version please use mode B.

A. Creating a session database using SQL files
In the ASP.net 1.0 and 1.1 versions, this is the only way to do this. For 2.0 and above, use the Aspnet_regsql.exe tool. (Of course this method is also General 2.0 version)
. NET provides a database installation script that can be found in the machine's Windows folder:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ InstallSqlState.sql
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ Installsqlstatetemplate.sql
Depending on the version of ASP.net, you need to use a different SQL script. Asp. NET includes 1.1 and 2.0 two versions, which can be found in different versions of the folder.
InstallSqlState.sql is the database "[ASPState]" that creates the default name. This SQL can be run directly.
Installsqlstatetemplate.sql can save data by using the database that you specify. This SQL needs to be modified and run, opening the SQL file to replace [Databasenameplaceholder] with its own specified database name.
You do not need to specify a database when performing installsqlstate.sql, which can be executed on any database. This SQL creates a new database of its own

B. Using the Aspnet_regsql.exe tool
ASP.net version 2.0 Microsoft has provided aspnet_regsql.exe tools to facilitate the configuration of the session database. The tool is located in the system root \microsoft.net\framework\ version number folder on the WEB server.
Use examples:
aspnet_regsql.exe-s.-U sa-p 123456-ssadd-sstype P
-S parameter:
Represents the database instance name. You can use the "." Represents the native.
-U and-p parameters:
Represents a user name and password.
-E parameter:
You can then select a group in-u–p with-E. –e means that the current system user logs on to the database through Windows authentication, and-u-p logs on to the database using SQL Server users.
-ssadd/–ssremove Parameters:
-ssadd means that the session database is added and-ssremove indicates that the session database is removed.
sstype Parameters:

Options

Description

T

Store session data in the SQL Server tempdb database. This is the default setting. If you store session data in the tempdb database, session data will be lost when you restart SQL Server.

P

Store session data in the ASPState database, rather than in the tempdb database.

C

Stores session data into a custom database. If you specify the C option, you must also use the- d option to include the name of the custom database.

(2) Session Client Settings
This room is also required for the Web application to modify the <sessionState> node in web.config. If you use the default database (ASPState library), configure the following:

Copy Code code as follows:

<sessionstate
mode= "SQL Server"
Sqlconnectionstring= "server=192.168.9.151; Uid=sa; pwd=123456; "
/>

If you use a custom database name, you also need to develop the Allowcustomsqldatabase property and specify the database in the database connection string:
Copy Code code as follows:

<sessionstate
mode= "SQL Server"
Allowcustomsqldatabase= "true"
Sqlconnectionstring= "server=192.168.9.151; Database=myaspstate;uid=sa; pwd=123456; "
/>

Six. Usage experience and skill summary
Here is a summary of the various experiences and techniques of SessionID, session_end time, Statserver mode, and SQL Server mode.
(1) stateserver mode:
1. In the Web farm, make sure that you have the same <machineKey> on all Web servers
2. Objects to be saved in the session are serializable.
3. The Web site application path (such as \lm\w3svc\2) in the maintenance session State,iis metabase on different Web servers in the Web farm should be consistent on all servers (case sensitive).
4. ASP. NET processing session is a HTTPMODUEL module configured in Machine.config, and in the Config folder in the. NET installation directory, view Web.config (version 1.1 is in Machine.config):
Copy Code code as follows:

... <add name= "session" type= "System.Web.SessionState.SessionStateModule"/>
...

Verify that the module exists.
5.StateServer does not support load balancing, so you can enjoy the high performance and security of SQL Server if you use SQL Server mode for large concurrency. Although storage efficiency will decrease.
6. The machinekey of all machines need to be the same. Configure in Machine.config:
Copy Code code as follows:

<machinekey
validationkey= "1234567890123456789012345678901234567890AAAAAAAAAA"
decryptionkey= "123456789012345678901234567890123456789012345678"
validation= "SHA1"
decryption= "Auto"
/>

(2) SQL Server mode:
1. Objects to be saved in the session are serializable.
2. If you use the default database, users of the database link strings in the client configuration file need to have Dbowner permissions for the ASPState and tempdb two libraries.
3. In SQL Server mode, session expiration is done by the SQL Agent using a registration task to confirm that the SQL Agent is already running. Failure to clean up expired session data can result in increased database data.
4. If you are using SQL Server mode, the asp.net application path for each server in the Web farm must be the same. Please synchronize the Web site application path for all Web servers in the Web farm in the IIS metabase. The capitalization must be the same, because the Web site's application path is case-sensitive.
5. The machinekey of all machines need to be the same. Configure in Machine.config:
Copy Code code as follows:

<machinekey
validationkey= "1234567890123456789012345678901234567890AAAAAAAAAA"
decryptionkey= "123456789012345678901234567890123456789012345678"
validation= "SHA1"
decryption= "Auto"
/>

(3) session:
1. You cannot share sessions between ASP.net and ASP directly through the session server. Please use the solution offered by Microsoft:
Http://msdn.microsoft.com/zh-cn/library/aa479313.aspx
2. Unable to share session between different applications or different virtual directories of a Web site
3. The expiration time of the session is the sliding time.
4. The session store. NET with the best value type performance. Storing objects can degrade performance.
(4) SessionID:
1.SessionID can also be saved on the URL, setting the Cookiesless property of the System.web/sessionstate node in the Web.config file:
Copy Code code as follows:

<sessionstate
Cookieless= "UseUri"
/>

2. Generally after the session timeout or deletion, the SessionID remain unchanged. Because the session expires, the data is purged on the server side, but SessionID is saved in the user's browser, so the SessionID in the HTTP header remains unchanged as long as the browser is not closed.
3. When you close the browser and then visit again, SessionID will be different.
4. Each open a IE6 window, SessionID are different, in the IE6 two window sessions can not be shared.
The 5.FireFox tabs and new Firefox windows, SessionID are the same and can be shared on the FF window and tab.
6. For pages that contain frameset, such as:
Copy Code code as follows:

<frameset cols= "25%,50%,25%" >
<frame src= "Sessionid.aspx" >
<frame src= "Sessionid.aspx" >
<frame src= "Sessionid.aspx" >
</frameset>

If the suffix name is. htm and the. htm file is not given to asp.net ISAPI processing, then the server speed generates a different SessionID per frame page, and then the same is equal to the last SessionID.
The solution is to change the. htm suffix to. aspx, or to the. htm file to asp.net ISAPI processing.
(5) Session_End event:
1. Session_End only available in InProc mode
2. Close the browser, Session_End is not triggered. HTTP is a stateless protocol, and the server has no way of knowing if your browser has been turned off.
3. Session_End is triggered when the session expires or calls Session.Abandon. Session.clear () Only clears the data, but does not delete the sessions.
4. Session_End is triggered by a background thread and runs with the worker process account. Therefore, the program does not notify the error that occurred.
5. Access to the database in Session_End is a matter of permissions. The Session_End is run with the running worker process (aspnet_wp.exe) account, which can be specified in Machine.config. Therefore, in Session_End, if you are using integrity security to connect to SQL, it will use the worker process account identity connection, which may cause a logon failure.
6. Because the session_end has a separate thread, the HttpContext object (Request,response,server, and so on) cannot be used in session_end, that is, it cannot be used Methods such as Response.Redirect and Server.Transfer.

Seven. Summary
I have used SQL Server mode to implement session sharing for multiple servers in the company, and server restart will not cause the user to restart the process (the scheduled session will not be lost). I hope this article is helpful to the specific session server builders.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.