1024programmer Java Asp.net implements Session distributed storage (Redis, Mongodb, Mysql, etc.) sessionStateCustom

Asp.net implements Session distributed storage (Redis, Mongodb, Mysql, etc.) sessionStateCustom

For asp.net programmers, Session storage methods include InProc, StateServer, SQLServer and Custom, but Custom is rarely mentioned. But Custom is indeed the best, the most practical and flexible way at present, because Custom can realize session storage in various situations, which is especially important for large websites. It is the best way to solve session loss and session efficiency, and it is also the best way to achieve single-use session storage. The best way to log in is to click. There are a lot of advantages and disadvantages of InProc, StateServer and SQLServer on the Internet, so I won’t explain them in detail here.

Two important points

1. First of all, it’s about Session storage. Session storage is not what we imagined. When setting up Session, we immediately insert or modify data into the data container. When we get the value of Session, we immediately go to the data container to get the value. This This understanding is wrong (this is how I understood it before). Later I thought there was no need to do this, and it would greatly affect efficiency. Asp.net’s Session implementation method is to obtain data before each request, and set the Session value when the request logic code ends. Therefore, the Session modifies the data container Simple meaning only twice. This may involve pipeline flow.

2. The second one is about the asynchronous problem of Asp.net website. When we do not set the status of Session to read-only, the requests of each of our users are actually synchronous, which means that each There can only be one request response at the same time when a user requests the website. Understanding this will help you understand the concept of locking required in subsequent implementation methods.

SessionStateStoreProviderBase

SessionStateStoreProviderBase is a member provided by the asp.net framework for us to store the members required by the Session provider (that is, this class is implemented). The InProc, SQLServer, and StateServer we know all implement this abstract class. Inheriting this class requires multiple abstract methods to be implemented. It is not necessary to implement each of these multiple methods, we only focus on what we need to implement. To put it simply, it is the addition, deletion, modification and query (CRUD) of Session data. For details about SessionStateStoreProviderBase, please refer to https://msdn.microsoft.com/zh-cn/library/system.web.sessionstate.sessionstatestoreproviderbase(v=vs.100).aspx

Members

Description

InitializeRequest method

Take the HttpContext instance of the current request as input and perform all initialization operations necessary for the session state storage provider.

EndRequest method

Take the HttpContext instance of the current request as input and perform any cleanup operations necessary for the session state storage provider.

Dispose method

Release all resources no longer used by the session state storage provider.

GetItemExclusive method

Uses the HttpContext instance of the current request and the SessionID value of the current request as input. Retrieve the session’s values ​​and information from the session data store and lock the session item data in the data store for the duration of the request. The GetItemExclusive method sets several output parameter values ​​that notify the calling SessionStateModule of the status of the current session state item in the data store.

If no session item data is found in the data store, the GetItemExclusive method sets the locked output parameter to false and returns null. This will cause the SessionStateModule to call the CreateNewStoreData method to create a new SessionStateStoreData object for the request.

If session item data is found in the data store but is locked, the GetItemExclusive method will locked output parameter Set to true, set the lockAge output parameter to the difference between the current date and time and the item’s lock date and time, set lockId The output parameter is set to the lock identifier retrieved from the datastore and returns null. This will cause the SessionStateModule to call the GetItemExclusive method again after half a second to attempt to retrieve session item information and obtain a lock on the data. If the setting value of the lockAge output parameter exceeds the ExecutionTimeout value, the SessionStateModule will call ReleaseItemExclu224 if (session == null)
225 {
226 return null;
227 }
228
229 // Determine whether the session is in ReadOnly mode, not readonly mode Determine whether to lock or not
230 if (isExclusive)
231 {
232 // If the session item data is found in the data store but is locked, the GetItemExclusive method will The locked output parameter is set to true,
233 // and the lockAge output parameter is set to the current date and time and the lock date and time of the item. time difference, sets the lockId output parameter to the lock identifier retrieved from the data store, and returns nul
234 if (session.Locked)
235 {
236 locked = true;
237 lockAge = session.LockDate – DateTime.Now;
238 lockId = session.LockId;
239 return null;
240 }
241 }
242
243 // Determine whether it has expired
244 if (session.Expires < DateTime.Now)
245 {
246 db.ASPStateTempSessions.Remove(session);
247 return null;
248 }
249
250 // Processing values
251 lockId = lockId == null ? 0 : (int)lockId + 1 span>;
252 session.Flags = (int)SessionStateActions.None;
253 session.LockId = Convert.ToInt32(lockId);
254
255 // Get timeout
256 var timeout = actiOns== SessionStateActions.InitializeItem ? _expiresTime.TotalMinutes : session.Timeout;
257
258 // Get SessionStateItemCollection
259 SessionStateItemCollection sessiOnStateItemCollection= null;
260
261 // Get the value of Session
262 if (actiOns== SessionStateActions.None && !string.IsNullOrEmpty(session.SessionItem))
263 {
264 sessiOnStateItemCollection= Deserialize((session.SessionItem));
265 }
266
267 item = new SessionStateStoreData(sessionStateItemCollection ?? new SessionStateItemCollection(), SessionStateUtility.GetSessionStaticObjects(context), (int)timeout);
268
269 return item;
270
271 }
272
273 }
274
275
276 # region Serializes and deserializes the value of Session
277 ///


278 /// Deserialize Session data
279 ///


280 ///
281 ///
282 public SessionStateItemCollection Deserialize(string item)
283 {
284 MemoryStream stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(item));
285 SessionStateItemCollection collection = new SessionStateItemCollection();
286 if (stream.Length > 0)
287 {
288 BinaryReader reader = new BinaryReader(stream);
289 collection = SessionStateItemCollection.Deserialize(reader);
290 }
291 return collection;
292 }
293
294 ///


295 /// Serialize Session data
296 ///


297 ///
298 ///
299 public string Serialize(SessionStateItemCollection items)
300 {
301 MemoryStream ms = new MemoryStream();
302 BinaryWriter writer = new BinaryWriter(ms);
303 if (items != null)
304 items.Serialize(writer);
305 writer.Close();
306 return System.Text.Encoding.ASCII.GetString(ms.ToArray());
307 }
308
309 #endregion
310
311
312 public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
313 {
314 return true;
315 }
316 public override void InitializeRequest(HttpContext context)
317 {
318 }
319 public override void EndRequest(HttpContext context)
320 {
321 }
322 public override void Dispose()
323 {
324 }
325
326 }
Finally configure web.config system.web/sessionState

1 <sessionState mode="Custom"   customProvider="mySessionProvider">
2 < providers>
3 <add name="mySessionProvider" type="CustomSessionState.MyCustomSessionStateStoreProvider,CustomSessionState"/>
4 </providers>
5 </ sessionState>

Github address

https://github.com/Emrys5/Asp.net-CustomSessionState

Finally, Please recommend

moryStream(System.Text.Encoding.ASCII.GetBytes(item));
285 SessionStateItemCollection collection = new SessionStateItemCollection();
286 if (stream.Length > 0)
287 {
288 BinaryReader reader = new BinaryReader(stream);
289 collection = SessionStateItemCollection.Deserialize(reader);
290 }
291 return collection;
292 }
293
294 ///


295 /// Serialize Session data
296 ///


297 ///
298 ///
299 public string Serialize(SessionStateItemCollection items)
300 {
301 MemoryStream ms = new MemoryStream();
302 BinaryWriter writer = new BinaryWriter(ms);
303 if (items != null)
304 items .Serialize(writer);
305 writer.Close();
306 return System.Text.Encoding.ASCII.GetString(ms.ToArray());
307 }
308
309 #endregion
310
311
312 public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
313 {
314 return true;
315 }
316 public override void InitializeRequest(HttpContext context)
317 {
318 }
319 public override void EndRequest(HttpContext context)
320 {
321 }
322 public override void Dispose()
323 {
324 }
325
326 }
Finally configure web.config system.web/sessionState

1 <sessionState mode="Custom"   customProvider="mySessionProvider">
2 < providers>
3 <add name="mySessionProvider" type="CustomSessionState.MyCustomSessionStateStoreProvider,CustomSessionState"/>
4 </providers>
5 </ sessionState>

Github address

https://github.com/Emrys5/Asp.net-CustomSessionState

Finally, Please recommend

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/asp-net-implements-session-distributed-storage-redis-mongodb-mysql-etc-sessionstatecustom/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

The latest and most comprehensive programming knowledge, all in 1024programmer.com

© 2023 1024programmer - Encyclopedia of Programming Field
Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us