- 實作Session時通常會使用MemoryCache, MsSql, Redis,如果不考慮高併發的話用MemoryCache自然是最好,但如果考慮到高併發的話就只能選擇後兩者,但MsSql在效能上遠遠不及Redis所以也就不考慮MsSql了
MemoryCache實作Session
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27public class Startup
{
public Startup(IConfiguration configuration)
{
var builder = new ConfigurationBuilder();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseMvc();
}
}高併發下AB站台去跟Redis要Session會發現同Cookie下A站台寫資料進去後,B站台會要不到資料,原因是每個.NetCore跟Redis要Session加密的方式不一樣,所以包併發站台必須得共享密鑰才可取到相同的Seesion資料,可以利用Microsoft.AspNetCore.DataProtection.Redis協助我們達成。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34public class Startup
{
public Startup(IConfiguration configuration)
{
var builder = new ConfigurationBuilder();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var redis = ConnectionMultiplexer.Connect("Redis Connection String");
services.AddDataProtection()
.SetApplicationName("session_application_name")
.PersistKeysToRedis(redis, "DataProtection-Keys");
services.AddDistributedRedisCache(o =>
{
o.Configuration = "Redis Connection String";
});
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseMvc();
}
}