负载均衡环境下的ServiceStack会话处理

3

我在我的一个项目中使用ServiceStack作为基础库。

我将我的应用程序分为API和WEB应用程序,它们是分开的项目和存储库。

身份验证应该在API层进行,并且应该在那里缓存。我在API服务器中使用Ormlite缓存客户端。

在API AppHost.cs文件中:

var dbFactory = new OrmLiteConnectionFactory("ConnectionString",SqlServerDialect.Provider);
container.RegisterAs<OrmLiteCacheClient, ICacheClient>();
container.Resolve<ICacheClient>().InitSchema();
Plugins.Add(new AuthFeature(() => new APISession(),
  new IAuthProvider[] {
    new APICredentialsAuthProvider(new AppSettings())
 }));

在 APICredentialsAuthProvider 中,我保存了会话,并将其存储在 CacheEntry 表中。
通过 ajax 调用 apiurl/auth 对用户进行身份验证,在返回的 AuthenticateResponse 中带有 sessionId。 我将此 sessionId 更新为 cookie 的 s-id,并在预请求过滤器中根据请求类型更新为 ss-id 或 ss-pid。
//Inside Web application apphost
this.PreRequestFilters.Add((req, res) =>
{
  System.Net.Cookie cookie = req.Cookies["s-id"];
  req.Cookies["ss-id"] = cookie;
  req.SetSessionId(cookie.Value)
});

这种方法并不会从缓存中获取会话,我在使用Ormlite和Web和Api应用程序中提供了相应的配置。

那么,最好的方法是什么?

然而,我可以通过使用缓存客户端来访问会话。

//Inside Web application apphost
this.PreRequestFilters.Add((req, res) =>
{
  System.Net.Cookie cookie = req.Cookies["s-id"];
  req.Cookies["ss-id"] = cookie;
  req.SetSessionId(cookie.Value);
 APISession cachedSession = GetCacheClient(req).Get<APISession(SessionFeature.GetSessionKey(cookie.Value));
 WEBSession session.PopulateWith<WEBSession, APISession>(cachedSession);

});

这个方案的运行很好,我可以获取会话,但是将其放在预请求过滤器中会增加 Web 应用程序对数据库的调用(每个请求都要调用一次)。

有没有其他可用的方案来实现同样的效果呢?

提前致谢!

1个回答

3
如果您正在负载均衡多个Web应用程序,并且这些应用程序位于相同的域后面,则使用任何分布式缓存提供程序(如OrmLiteCacheClient)将在向任一应用程序发出请求时发送ServiceStack的ss-id/ss-pid Cookies:
http://example.org/app1 -> http://internal:8001/
                  /app2 -> http://internal:8002/
                  /app3 -> http://internal:8003/                     

只要每个应用程序都配置了相同的OrmLiteCacheClient,在一个应用程序中创建的会话将在所有3个应用程序中可见。

您可以通过将其设置在IRequest.Items上来防止检索该请求的会话以进行进一步的DB访问,例如:

req.Items[Keywords.Session] = session;

那么,对于该请求的任何Session访问都将从项字典中解析,而不是直接查询数据库。

另一种可选的身份验证解决方案是使用无状态的JWT Auth Provider,它将使您能够在所有3个应用程序中进行身份验证。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接