简体   繁体   English

如何在分布式应用程序中管理会话

[英]How to manage sessions in a distributed application

I have a Java web application which is deployed on two VMs.我有一个部署在两个 VM 上的 Java Web 应用程序。 and NLB (Network Load Balancing) is set for these VMs.并且为这些 VM 设置了 NLB(网络负载平衡)。 My Application uses sessions.我的应用程序使用会话。 I am confused that how the user session is managed in both VMs.我很困惑如何在两个 VM 中管理用户会话。 ie For Example- If I make a request that goes to VM1 and create a user session.即例如 - 如果我发出一个请求,该请求转到 VM1 并创建一个用户会话。 Now the second time I make request and it goes to VM2 and want to access the session data.现在我第二次发出请求,它转到 VM2 并想要访问会话数据。 How would it find the session which has been created in VM1.它如何找到已在 VM1 中创建的会话。

Please Help me to clear this confusion.请帮我清除这个困惑。

There are several solutions:有几种解决方案:

  • configure the load balancer to be sticky: ie requests belonging to the same session would always go to the same VM.将负载平衡器配置为粘性:即属于同一会话的请求将始终转到同一个 VM。 The advantage is that this solution is simple.优点是这个解决方案很简单。 The disadvantage is that if one VM fails, half of the users lose their session缺点是如果一个虚拟机出现故障,一半的用户会丢失他们的会话
  • configure the servers to use persistent sessions.将服务器配置为使用持久会话。 If sessions are saved to a central database and loaded from this central database, then both VMs will see the same data in the session.如果会话保存到中央数据库并从该中央数据库加载,则两个 VM 将在会话中看到相同的数据。 You might still want to have sticky sessions to avoid concurrent accesses to the same session您可能仍然希望使用粘性会话来避免对同一会话的并发访问
  • configure the servers in a cluster, and to distribute/replicate the sessions on all the nodes of the cluster配置集群中的服务器,并在集群的所有节点上分发/复制会话
  • avoid using sessions, and just use an signed cookie to identify the users (and possibly contain a few additional information).避免使用会话,只使用签名的 cookie 来识别用户(并且可能包含一些附加信息)。 A JSON web token could be a good solution. JSON 网络令牌可能是一个很好的解决方案。 Get everything else from the database when you need it.在需要时从数据库中获取其他所有内容。 This ensures scalability and failover, and, IMO, often makes things simpler on the server instead of making it more complicated.这确保了可扩展性和故障转移,而且,IMO 通常使服务器上的事情变得更简单,而不是使其变得更复杂。

You'll have to look in the documentation of your server to see what is possible with that server, or use a third-party solution.您必须查看服务器的文档以了解该服务器的功能,或使用第三方解决方案。

我们可以使用分布式Redis来存储会话,这可以解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM