Go Session Server Configuration Guide and usage experience

Source: Internet
Author: User

This article transferred from: http://www.cnblogs.com/zhangziqiu/archive/2009/03/26/SessionServer.html

I. Summary

All Web programs will use the session to save the data. Using a separate session server can solve the session sharing problem in the load balancing scenario. This article introduces several methods of establishing session server under the. NET Platform, and introduces various experiences and techniques in using the 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.

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 novice 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, so when we save cookies, we must be careful not to cause SessionID objects because of the size and number of cookies. In our program, SessionID cookies have special handling:

        <summary>///write cookies. ///</summary> ///<param name= "Day" ></param> ///<returns></returns> public bool Setcookie (int day) {string cookiename = GetType (). ToString (); HttpCookie Sessioncookie = null; //the SessionId for backup. 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 part of the code. Keep Backup SessionID and retrieve SessionID logic
                        If the total number of cookies exceeds 20, rewrite the Asp.net_sessionid to prevent the session from being lost.             null)            {                string. Empty) {HttpContext.Current.Response.Cookies.Remove (true;}  

Three. Several ways to build a session server

The session can be shared between multiple Web servers by saving sessions in a separate server. Although we can also develop our own session storage system, it is more convenient to use ASP.

. NET offers 5 ways to save Seission:

Mode Name

Storage mode Performance

Off

Set to do not use session function

No

InProc

Set to store the session in-process, that is, the storage method 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

Sql server

Settings to store the session in SQL Server.

Performance Loss 10-20%

Customer

Self-Customized storage solutions

Determined by the implementation method

We can configure the session storage method used by the program in Web. config. By default, InProc is saved in the IIS process. About off, InProc and customer do not explain this article. Related articles can be found on the Internet.

The following focuses on StateServer and SQL Server applications.

Four. Using StateServer mode to build session server (1) server-side configuration

1. Start the ASP. (The default state for this service is manual. Modified to Auto and start.)

2. Modify the registry: [Hkey_local_machine\system\controlset001\services\aspnet_state\parameters]

Set allowremoteconnection = 1, set Port = 42424 (decimal, default is 42424)

Port is the port number of the service

Allowremoteconnection Indicates whether other machines are allowed to connect, 0 for native use only, and 1 for other machines to use.

(2) Client settings

In Web. config, we need to modify the <sessionState> node for <configuration>/<system.web>. If not

Not added (by default, InProc mode is used)

<modestateconnectionstringcookielesstimeout= "/>    " 

The above parameters can be modified as needed.

Five. Setting up session server (1) server-side configuration using SQL Servers mode

There are two ways to build session servers using SQL Server mode. For the ASP. NET 1.0 and 1.1 versions, use mode A, 2.0 that is, use mode B for the above version.

A. Creating a session database with a SQL file

in ASP. 1.0 and 1.1, you can only use this method. For 2.0 and later, use the Aspnet_regsql.exe tool. (Of course this method is also generic 2.0 version)

. NET provides a database installation script that can be found in the Windows folder of your machine:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ InstallSqlState.sql

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ Installsqlstatetemplate.sql

Different SQL scripts are required depending on the version of ASP. Asp. NET has 1.1 and 2.0 two versions, and you can find these two SQL 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 using a database of its own designation. This SQL needs to be modified to run after you open the SQL file to replace [Databasenameplaceholder] with the name of the database you specified.

You do not need to specify a database when executing installsqlstate.sql and can be executed on any database. This SQL creates a new database on its own

B. Using the Aspnet_regsql.exe tool

After the ASP. NET 2.0 version, Microsoft provides the Aspnet_regsql.exe tool to easily configure the session database. The tool is located in the system root \microsoft.net\framework\ version number folder on the WEB server.

Examples of Use:

Aspnet_regsql.exe-s. -U sa-p 123456-ssadd-sstype P

  

-S parameter:

Represents the database instance name. You can use "." Represents the native.

-U and-p parameters:

Represents a user name and password.

-E parameter:

You can select a group in-u–p and-e again. –e represents logging in to the database with the current system user through Windows authentication, and-u-p is logging on to the database using SQL Server users.

-ssadd/–ssremove Parameters:

-ssadd indicates that the session database is added, and-ssremove represents the session database removal.

Sstype Parameters:

Options

Description

T

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

P

The session data is stored in the ASPState database instead of stored in the tempdb database.

C

Store session data in 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 to modify the <sessionState> node in Web. config. If you use the default database (ASPState library), the configuration is as follows:

    <sessionstate      mode= "SQL Server"      sqlconnectionstring/>    

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

    <sessionstate      mode= "SQL Server"      allowcustomsqldatabasesqlconnectionstring/ >     

Six. Summary of the use of experience and skills

Below 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. The objects to be saved in the session are serializable.

3. In order to maintain a Web site application path (such as \lm\w3svc\2) in the session State,iis metabase on different Web servers in the Web farm, it should be consistent (case sensitive) on all servers.

4. ASP. NET processing session is the Httpmoduel module configured in Machine.config, in the Config folder under the. NET installation directory, view the Web. config (version 1.1 is in Machine.config):

        <httpmodules>            ...  
            <nametype= "System.Web.SessionState.SessionStateModule"/>                ...
        </httpmodules> 

Verify that the module exists.

5.StateServer does not support load balancing, so if SQL Server mode is recommended for large concurrency, you can enjoy the high performance and security of SQL Server. Although storage efficiency decreases.

6. You need to make the machinekey of all machines the same. Configure in Machine.config:

<validationkeydecryptionkeyvalidationdecryption/>    
(2) SQL Server Mode:

1. The objects to be saved in the session are serializable.

2. If you use the default database, the user who has a database link string in the client configuration file needs to have Dbowner permissions for the ASPState and tempdb two libraries.

3. In SQL Server mode, session expiration is performed by the SQL Agent using a registration task, to confirm that the SQL Agent is already running. Otherwise, the expired session data cannot be cleaned up, causing the database data to increase continuously.

4. If you are using SQL Server mode, the ASP. NET application path must be the same for individual servers in a Web farm. Synchronize the application path of the Web site to all Web servers in the Web farm in the IIS configuration database. The case must be the same, because the Web site's application path is case-sensitive.

5. You need to make the machinekey of all machines the same. Configure in Machine.config:

<validationkeydecryptionkeyvalidationdecryption/>    
(3) Session:

1. You cannot share a session 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. The session cannot be shared between different applications or different virtual directories of a Web site

3. The session expiration time is the sliding time.

4. Session store. NET comes with a value type that has the best performance. Storage objects can degrade performance.

(4) SessionID:

1.SessionID can also be saved on a URL, setting the Cookiesless property of the System.web/sessionstate node in the Web. config file:

    <sessionstate      cookieless= "UseUri"      />   

2. The sessionid remains unchanged after the session expires or is deleted. Because the session expires after the data is purged on the server side, but SessionID is saved on the user's browser, the SessionID in the HTTP header remains the same as long as the browser does not close.

3. After you close the browser and then visit, SessionID will be different.

4. Each open a IE6 window, SessionID are different, in IE6 in the session of two windows can not be shared.

The 5.FireFox tab and the new Firefox window, SessionID are the same, and can be shared on the windows and tabs of the FF.

6. For pages that contain frameset, for example:

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

If the suffix name is. htm and the. htm file is not assigned to ASP. NET ISAPI processing, then a different SessionID is generated on each frame page based on the server speed, and the same is equal to the last SessionID after the refresh.

The workaround is to change the. htm suffix to. aspx, or to give the. htm file to the ISAPI processing of ASP.

(5) Session_End Event:

1. Session_End 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 if your browser is closed.

3. Session_End is triggered when the Session expires due to time expiration or when calling Session.Abandon. Session.clear () is simply clearing the data but not deleting the session.

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 the database in Session_End to consider permissions issues. Session_End is run with an account running the worker process (aspnet_wp.exe), which can be specified in Machine.config. Therefore, in Session_End, if you use integrity security to connect to SQL, it will use the worker process account identity connection, which may cause login failures.

6. Because Session_End is a separate thread, it is not possible to use HttpContext objects in Session_End (Request,response,server objects are in HttpContext), which means they 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 the server reboot will not cause the user to start the process again (the session required by the booking process will not be lost). I hope this article will be helpful to the specific session server building personnel.

Reference documents:

All applications that use a SQL database SQL Server session state may cause bottlenecks

Http://support.microsoft.com/kb/836680/zh-cn

Analysis of Session implementation principle in ASP [1]/[2]

Http://www.cnblogs.com/flier/archive/2004/08/04/30226.html

Http://www.cnblogs.com/flier/archive/2004/08/07/30902.html

Understanding Session state Mode +asp.net session Loss FAQ [Translate]

Http://www.cnblogs.com/tonyqus/archive/2006/10/24/522618.html

Go Session Server Configuration Guide and usage experience

Related Article

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.