Analysis of session implementation in ASP.NET [2] Status Manager

xiaoxiao2021-03-06  103

Original: http://www.blogcn.com/User8/flier_lu/index.html? Id = 3213970

Status management is originally a very good thing, hey, but but some manufacturers are always considered when they are realized. For example, the status management implementation of MS in ASP is rotatable, because only a memory-based state management within a process is implemented, there is a lot of problems: 1. All session data is saved in the process of Web services, resulting in servers Support for the number of sessions is restricted by the server memory resources, and the memory is not occupied by a large number of non-active sessions. 2. Server process crashes will result in all session data loss. 3. The session cannot be used across the process or in load balancing, unless the load balancing technology guarantees that the same user can be routed to the same machine. Even if this is not allowed to ensure the loss of session data caused by the server crash. 4. Requires cookie support, and now many people closes the support of cookie and JS in the browser now because of security issues. For this purpose, the user has to manually handle the session information to the external database to ease similar issues in the session ID. In ASP.NET, these issues are considered when designing these problems: 1. Support state management outside the process, through standalone status management services or SQL Server status server management session status 2. Support does not use cookie Status maintenance, by automatically adding a session ID in the URL to avoid using cookie 3. Synchronize the use of session information to implement these features when supported by a stand-alone status management service or SQL Server status server to support load balancing, it is the sessionStateModule.initModuleFromConfig mentioned by the previous section. In the function, implement the four different status managers selected according to the SESSIONSTATE tagged Mode property.

The following program code is:

OFF mode disables session management, and ASP.NET also allows session support status by the EnablesTate attribute fine-grained management page via the ENABLESSTATE attribute

The following is the program code: <% @ page enablessionstate = "true | false | readonly"%>

InProc mode is compatible with the previous ASP policy, the memory-based session state management is implemented in the same process space in ASP.NET, and the speed is the fastest but is subject to ASP;

The StateServer mode The ASP.NET STATE Service service (ASPNET_STATE.EXE) installed by ASP.NET, which responds to session stating services as StateConnectionstring;

SQLServer mode The SQL Server server specified by SqlConnectionsTRING (using the Tempdb memory database) or independent table (in InstallPstsqlState.sql) to maintain session status (using a TEMPDB memory database) or independent table (in installpersistState.sql). These four different state managers, with the test of the "Performance Tuning and Optimizing ASNET Appliation" book, the relative value is as follows:

The following is quoted:

Table 4-1: Normalized TTLB (Time to Last Byte) by Session State Mode (In MilliseConds Per 100 Requests)

Concurrent Browsers Mode = Off Mode = Inproc Mode = StateServer Mode = SQLServer

1 7.81 4.54 8.27 8.47

5 28.28 20.25 27.25 29.29

10 89.38 46.08 77.29 85.11

Table 4-2: Average Requests Per Second by Session State Mode

Concurrent Browsers Mode = Off Mode = Inproc Mode = StateServer Mode = SQLServer

1 18.86 24.17 18.31 18.11

5 21.66 25.74 21.54 21.34

10 17.23 23.8 18.11 17.6

It can be seen that whether it is from TTLB or average average request, the performance of the processed state manager can be accepted, of course, it also needs to be optimized when writing code for status management. However, to use Process Output Status Manager, the object saved in the session is subject to restrictions that must be improved in binary serialization.

From a use perspective, the status manager is actually established by the HTTPSessionModule mentioned by the previous section, and provides access by the HTTPSESSTATE interface, the structure is as follows:

MSDN

The underpinnings of the session state version is very detailed in detail the principle and use of several different status managers, which is not coming.

From the implementation point of view, SessionStateModule.InitModuleFromConfig function mentioned in the previous section, according to the configuration file manager state model were established System.Web.SessionState.InProcStateClientManager, System.Web.SessionState.OutOfProcStateClientManager and System.Web.SessionState . SqlStateClientManager Instances of the Three Class Status Manager. They all inherit from the System.Web.SessionState.StateClientManager abstraction class and improve Status Management Services to HTTPApplication via the System.Web.SessionState.IstateClientManager interface. The iStateClientManager interface is a unified management interface of the status manager, mainly providing the following features:

The following program code is: internal interface System.Web.SessionState.IStateClientManager.IStateClientManager {// configuration manager state manager void ConfigInit (SessionStateSectionHandler.Config config, SessionOnEndTarget onEndTarget); // save for later use Example SessionStateModule void SetStateModule (SessionStateModule module ); void ResetTimeout (string id); void Dispose (); void Set (string id, SessionStateItem item, bool inStorage); // maintain state manager content IAsyncResult BeginGet (string id, AsyncCallback cb, object state); SessionStateItem EndGet ( IAsyncResult ar); IAsyncResult BeginGetExclusive (string id, AsyncCallback cb, object state); SessionStateItem EndGetExclusive (IAsyncResult ar); void ReleaseExclusive (string id, int lockCookie);}

The Configinit method is mainly in the initialization of the Status Manager to initialize it according to the configuration and will be responsible for the sessionOndTarget object instance responsible for the session state clearance (we will discuss in detail after the session status management implementation). For OutofProcStateClientManager and SqlStateClientManager, the connection to the external server is also initialized at this stage, and provides a time policy-based resource pool to maintain the connection;

ResetTimeout method Resets the timeout time of the specified session; for the InProcStateClientManager, this timeout is used by the cache object implemented by system.web.caching.cacheinternal type; OutofprocStateClientManager is sent directly to the external independent state management through the MakeRequest function constructor. Execute; SqlStateClientManager calls the stored procedure TempreSetTimeout update the expiration time expiRES field for the ASPSTATETEMPSESSIONS table;

If the Dispose method is the resource of the status manager, the code is to release the release of the resource pool in OutofprocStateClientManager and SQLStateClientManager; SET method stores the specified sessionStateItem stores in the id related session data, decided in accordance with the status state specified by instaged Whether the lock to this session is released if an abnormality. And implementation ResetTimeout similar, OutOfProcStateClientManager sends a request to external independent state manager; SqlStateClientManager call a stored procedure TempUpdateStateItemXXX updates the session state table expiration Expires field ASPStateTempSessions in a locked state Lock field, and status information SessionItemShort / SessionItemLong (were preserved 7,000 words Data below or above the section). If an exception occurs and set an Instrage tag, then call the TempreleaseStateItemExClusive release session lock.

The acquisition of data in the status manager is more complicated, and the IStateClientManager interface is used as an asynchronous call mode, and takes an exclusive acquisition data separately for increasing efficiency. The Status Manager implements a variety of tool methods that are implemented by universal base class System.Web.SessionState.StateClientManager to make it asynchronously. Then finally complete the operation through the GET and GetExClusive method by the implementation class. Getting data method InprocStateClientManager passes the cache; OutofprocStateClientManager passes the request; SQLStateClientManager is complete through the TempgetStateItemxxx stored procedure.

After learning the implementation and method of using the status server controlled by the sessionStateModule, let's take a look at how the upper HTTPSessionState is used.

Mandeep S Bhatia

ASP.NET Session Management INTERNALS describes the principle of completing status information management within HttpSessionState. HttpSessionState's ITEM properties are actually implemented through the SessionDictionary instance.

The following is the program code: public sealed class httpsessionState: ... {private sessionDictionary _dict; public object this [String name] {get {return_dict [name];} set {_dict [name] = value;}}}

And this SessionDictionary instance is completed in the sessionStateModule.CompleteAcquiRestate method that the HTTPSessionState instance is completed in the sessionStateModule.CompleTeAcquiRestate method mentioned in the previously mentioned completed session constructed:

The following program code is: public sealed class SessionStateModule: IHttpModule {private string _rqId; private SessionDictionary _rqDict; private HttpStaticObjectsCollection _rqStaticObjects; // static object, page tag set private int _rqTimeout; private bool _rqIsNewSession; private bool _rqReadonly; private HttpContext _rqContext; private SessionStateItem _rqItem; private void CompleteAcquireState () {if (! _rqItem = null) {if (_rqItem.dict = null!) {_rqDict = _rqItem.dict;} else {_rqDict = new SessionDictionary ();} _rqStaticObjects = ((_rqItem.staticObjects = null) _rqItem.staticObjects:! _rqContext.Application.SessionStaticObjects.Clone ()?); _rqTimeout = _rqItem.timeout; _rqIsNewSession = false; _rqInStorage = true _Rqstreamlength = _rqitem.streamlength;} else {_rqdict = new sessionDictionary (); _rqStaticObjects = _rqContext.Application.SessionStatico bjects.Clone (); _rqTimeout = SessionStateModule.s_config._timeout; _rqIsNewSession = true; _rqInStorage = false;} _rqDict.Dirty = false; _rqSessionState = new HttpSessionState (_rqId, _rqDict, _rqStaticObjects, _rqTimeout, _rqIsNewSession, SessionStateModule.s_config._isCookieless, SessionStateModule.s_config._mode, _rqreadonly; _rqcontext.items.add ("aspsession", _rqsessionState;}}

Several fields involved here, basically can correspond to the public properties provided by HTTPSESSTATE. It should be noted that httpsessionState.StaticObjects is the similar to the ASP.NET page; _rqreadonly is the <% @Page EnableState = "Readonly mentioned earlier "%> Tag setting. At this point, the use and implementation method of the status manager is basically analyzed, and the following is organized:

1. Construction: httpapplication calls the IhtModules initialization profile in the initialization process of the IHTTPModule interface to implement the IHTTPModule interface; where sessionStateModule is constructed and initialized as one of the modules; its initModuleFromConfig method is based on the status manager in the configuration file. Related configurations, constructs and initializes the corresponding status manager; and call the CompleteAcquiRestate method to complete the constructor of HttpSessionState based on various conditions.

2. Use: httpsessionState implements status data management of its Item attribute through SessionDictionary; SESSIONDICTIONARY itself is written back to the status manager by sessionStateModule.onReleaseState; other maintenance operations are also completed by the IstateClientManager interface of the SESSITIONSTATEMODULE call status manager.

3. Implementation: Status Manager gets an asynchronous call from an abstract base class StateClientManager; providing the interface to sessionStateModule to manage its initialization, release, and manage the interface through the IStateClientManager interface.

Although ASP.NET has made a lot of work, personal feelings are far less than enough. For example, InProc / OutofProc is actually in memory, just solves a problem of synchronization in reliability and data concentration; although SQL Server can solve the problem of synchronization in capacity, reliability, and data concentration, the efficiency is affected. This, .NET should learn from Java, such as Java

Ehcache and

Oscache provides a smooth configurable secondary (memory / hard disk) cache medium switching, and the latter also provides simple support for load balancing, in addition, there is a load balancing of IP multicast and other IP multicast, etc. implemented by JBoss. Implementation, etc., far exceeds the scope considered by the cache mechanism provided by ASP.NET. Although ASP.NET also has an independent caching mechanism, MS also proposes the reference implementation of Cache Application Block, but it is still a long, huh, huh.

转载请注明原文地址:https://www.9cbs.com/read-124465.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.045, SQL: 9