我正在尝试使用 Redis 在两个 C# 微服务之间共享会话。目前,RedisDB 仅添加格式为 AuthMicroservice:* 的密钥和 DataProtectionKeys(列表)条目。当第二个微服务尝试使用 HttpContext.Session.GetString("UserId") 检索会话时,它返回 null(它在 authmicroservices 中工作)。
这是我到目前为止所得到的: AuthMicroservice 中的会话配置(正在存储 cookie 会话)::
var redisConnectionString = builder.Configuration.GetConnectionString("RedisConnection");
var redis = redisConnectionString != null ? ConnectionMultiplexer.Connect(redisConnectionString) : null;
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "DataProtectionKeys");
builder.Services.AddStackExchangeRedisCache(option =>
{
option.Configuration = redisConnectionString;
option.InstanceName = "AuthMicroservice:";
});
// Configure Session
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(15);
options.Cookie.MaxAge = TimeSpan.FromDays(15);
options.Cookie.Name = "Session";
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
和 GameMicroservice 会话:
var redisConnectionString = builder.Configuration.GetConnectionString("RedisConnection");
var redis = redisConnectionString != null ? ConnectionMultiplexer.Connect(redisConnectionString) : null;
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "DataProtectionKeys");
builder.Services.AddStackExchangeRedisCache(option =>
{
option.Configuration = redisConnectionString;
option.InstanceName = "GameMicroservice:";
});
// Configure Session
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(15);
options.Cookie.MaxAge = TimeSpan.FromDays(15);
options.Cookie.Name = "Session";
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
可能导致此问题的原因是什么,两者都连接到同一个 Redis 数据库,以及如何在两个微服务之间正确共享会话?
首先,
option.InstanceName = "AuthMicroservice:";
必须相同。 另一个问题是您需要禁用AutomaticKeyGeneration,否则每次都会使用生成新密钥。
builder.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "DataProtectionKeys")
.DisableAutomaticKeyGeneration();
请注意,您可以启用 keygenerate 来启动。