微擎session储存方式mysql_Asp.net 实现Session分布式储存(Redis,Mongodb,Mysql等) sessionState Custom...

丁雅逸
2023-12-01

1 ///

2 ///自定义Session实现方式3 ///

4 public classMyCustomSessionStateStoreProvider : SessionStateStoreProviderBase5 {6 ///

7 ///获取配置文件的设置的默认超时时间8 ///

9 private staticTimeSpan _expiresTime;10

11 ///

12 ///获取Web.config 在sessionState设置的超时时间13 ///

14 staticMyCustomSessionStateStoreProvider()15 {16 System.Web.Configuration.SessionStateSection sessionStateSection = (System.Web.Configuration.SessionStateSection)System.Configuration.ConfigurationManager.GetSection("system.web/sessionState");17 _expiresTime =sessionStateSection.Timeout;18 }19

20 ///

21 ///创建新的存储数据22 ///

23 ///

24 ///

25 ///

26 public override SessionStateStoreData CreateNewStoreData(HttpContext context, inttimeout)27 {28 return new SessionStateStoreData(newSessionStateItemCollection(), SessionStateUtility.GetSessionStaticObjects(context), timeout);29 }30

31 ///

32 ///创建未初始化的项,就是初始化Session数据33 ///

34 ///

35 ///

36 ///

37 public override void CreateUninitializedItem(HttpContext context, string id, inttimeout)38 {39 using (SessionStateEF db = newSessionStateEF())40 {41 var session = newASPStateTempSessions42 {43 Created =DateTime.Now,44 Expires =DateTime.Now.AddMinutes(timeout),45 Flags = (int)SessionStateActions.InitializeItem,46 LockDate =DateTime.Now,47 Locked = false,48 SessionId =id,49 LockId = 0,50 Timeout =timeout51 };52 db.ASPStateTempSessions.Add(session);53 db.SaveChanges();54 }55 }56

57 ///

58 ///释放锁定的项,就是把锁定的Session的锁的状态清除掉59 ///

60 ///

61 ///

62 ///

63 public override void ReleaseItemExclusive(HttpContext context, string id, objectlockId)64 {65 using (SessionStateEF db = newSessionStateEF())66 {67 var session =db.ASPStateTempSessions.Find(id);68 if (session == null)69 {70 return;71 }72

73 //把locked设置为false

74 session.Locked = false;75 session.Expires = DateTime.Now +_expiresTime;76 db.SaveChanges();77 }78

79 }80

81 ///

82 ///删除Session,会在Session.Abandon()的时候调用83 ///

84 ///

85 ///

86 ///

87 ///

88 public override void RemoveItem(HttpContext context, string id, objectlockId, SessionStateStoreData item)89 {90 using (SessionStateEF db = newSessionStateEF())91 {92 var session =db.ASPStateTempSessions.Find(id);93 if (session == null)94 {95 return;96 }97

98 db.ASPStateTempSessions.Remove(session);99 db.SaveChanges();100 }101 }102

103 ///

104 ///设置超时时间105 ///

106 ///

107 ///

108 public override void ResetItemTimeout(HttpContext context, stringid)109 {110 using (SessionStateEF db = newSessionStateEF())111 {112 var session =db.ASPStateTempSessions.Find(id);113 if (session == null)114 {115 return;116 }117 session.Expires = DateTime.Now +_expiresTime;118 db.SaveChanges();119 }120 }121

122 ///

123 ///新建或者释放锁定的项并设置Session的值124 ///

125 ///

126 ///

127 ///

128 ///

129 ///

130 public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, boolnewItem)131 {132 using (SessionStateEF db = newSessionStateEF())133 {134 //判断是否是新建,如果是新建则和CreateUninitializedItem不同在于Timeout和有初始值。

135 if(newItem)136 {137 var session = newASPStateTempSessions138 {139 Created =DateTime.Now,140 Expires =DateTime.Now.AddMinutes(item.Timeout),141 Flags = (int)SessionStateActions.None,142 LockDate =DateTime.Now,143 Locked = false,144 SessionId =id,145 LockId = 0,146 Timeout =item.Timeout,147 SessionItem =Serialize((SessionStateItemCollection)item.Items)148 };149 db.ASPStateTempSessions.Add(session);150 db.SaveChanges();151 }152 else//释放锁定的项并设置Session的值

153 {154 var session = db.ASPStateTempSessions.FirstOrDefault(i => i.SessionId ==id);155 if (session == null)156 {157 return;158 }159

160 session.Expires =DateTime.Now.AddMinutes(item.Timeout);161 session.Locked = false;162 session.LockId =Convert.ToInt32(lockId);163 session.SessionItem =Serialize((SessionStateItemCollection)item.Items);164 db.SaveChanges();165 }166 }167 }168

169 ///

170 ///获取项,这个方式主要是把Session状态设置为只读状态时调用。171 ///

172 ///

173 ///

174 ///

175 ///

176 ///

177 ///

178 ///

179 public override SessionStateStoreData GetItem(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, outSessionStateActions actions)180 {181 return DoGet(false, context, id, out locked, out lockAge, out lockId, outactions);182 }183

184 ///

185 ///独占获取项,除了Session状态为只读时调用186 ///

187 ///

188 ///

189 ///

190 ///

191 ///

192 ///

193 ///

194 public override SessionStateStoreData GetItemExclusive(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, outSessionStateActions actions)195 {196 return DoGet(true, context, id, out locked, out lockAge, out lockId, outactions);197 }198

199 ///

200 ///获取Session的值201 ///

202 ///

203 ///

204 ///

205 ///

206 ///

207 ///

208 ///

209 ///

210 public SessionStateStoreData DoGet(bool isExclusive, HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, outSessionStateActions actions)211 {212 using (SessionStateEF db = newSessionStateEF())213 {214 //设置初始值

215 var item = default(SessionStateStoreData);216 lockAge =TimeSpan.Zero;217 lockId = null;218 locked = false;219 actions = 0;220

221 //如果数据存储区中未找到任何会话项数据,则GetItemExclusive 方法将 locked 输出参数设置为false,并返回 null。222 //这将导致 SessionStateModule调用 CreateNewStoreData 方法来为请求创建一个新的SessionStateStoreData 对象。

223 var session =db.ASPStateTempSessions.Find(id);224 if (session == null)225 {226 return null;227 }228

229 //判断session是否是ReadOnly 模式,不是readonly模式得判断是否锁住

230 if(isExclusive)231 {232 //如果在数据存储区中找到会话项数据但该数据已锁定,则GetItemExclusive 方法将 locked 输出参数设置为true,233 //将 lockAge 输出参数设置为当前日期和时间与该项锁定日期和时间的差,将 lockId 输出参数设置为从数据存储区中检索的锁定标识符,并返回 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 //判断是否过期

244 if (session.Expires

250 //处理值

251 lockId = lockId == null ? 0 : (int)lockId + 1;252 session.Flags = (int)SessionStateActions.None;253 session.LockId =Convert.ToInt32(lockId);254

255 //获取timeout

256 var timeout = actions == SessionStateActions.InitializeItem ?_expiresTime.TotalMinutes : session.Timeout;257

258 //获取SessionStateItemCollection

259 SessionStateItemCollection sessionStateItemCollection = null;260

261 //获取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 returnitem;270

271 }272

273 }274

275

276 #region 序列化反序列化Session的值

277 ///

278 ///反序列化Session的数据279 ///

280 ///

281 ///

282 public SessionStateItemCollection Deserialize(stringitem)283 {284 MemoryStream stream = newMemoryStream(System.Text.Encoding.ASCII.GetBytes(item));285 SessionStateItemCollection collection = newSessionStateItemCollection();286 if (stream.Length > 0)287 {288 BinaryReader reader = newBinaryReader(stream);289 collection =SessionStateItemCollection.Deserialize(reader);290 }291 returncollection;292 }293

294 ///

295 ///序列化Session的数据296 ///

297 ///

298 ///

299 public stringSerialize(SessionStateItemCollection items)300 {301 MemoryStream ms = newMemoryStream();302 BinaryWriter writer = newBinaryWriter(ms);303 if (items != null)304 items.Serialize(writer);305 writer.Close();306 returnSystem.Text.Encoding.ASCII.GetString(ms.ToArray());307 }308

309 #endregion

310

311

312 public override boolSetItemExpireCallback(SessionStateItemExpireCallback expireCallback)313 {314 return true;315 }316 public override voidInitializeRequest(HttpContext context)317 {318 }319 public override voidEndRequest(HttpContext context)320 {321 }322 public override voidDispose()323 {324 }325

326 }

 类似资料: