gpt4 book ai didi

jakarta-ee - 何时在无状态 session bean 上使用有状态 session bean?

转载 作者:IT老高 更新时间:2023-10-28 11:46:26 24 4
gpt4 key购买 nike

有状态 session bean 定义如下:

Stateful Session Beans The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client-bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state.

无状态 session bean 定义如下:

Stateless Session Beans A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client, but only for the duration of the invocation. When the method is finished, the client-specific state should not be retained. Clients may, however, change the state of instance variables in pooled stateless beans, and this state is held over to the next invocation of the pooled stateless bean. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client. That is, the state of a stateless session bean should apply accross all clients.

使用无状态 session bean 相对于有状态 session bean 的优势如下:

Because stateless session beans can support multiple clients, they can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients.

所以想到的问题是什么时候应该使用有状态 session bean?根据我对此事的天真理解,应该尽可能坚持使用无状态 session bean。

应该使用有状态 session bean 的候选对象是什么?有什么好的例子吗?

Session Bean

最佳答案

首先,您必须了解 bean 是如何在服务器上创建和处理的。

对于无状态 session bean,服务器可以在池中维护可变数量的实例。每次客户端请求这样的无状态 bean(例如通过方法)时,都会选择一个随机实例来服务该请求。这意味着如果客户端执行两个后续请求,则无状态 bean 的两个不同实例可能为请求提供服务。实际上,这两个请求之间没有 session 状态。此外,如果客户端消失,无状态 bean 不会被销毁,并且可以为来自另一个客户端的下一个请求提供服务。

另一方面,有状态 session bean 与客户端紧密相连。每个实例都被创建并绑定(bind)到单个客户端,并且只为来自该特定客户端的请求提供服务。碰巧的是,如果您在有状态 bean 上执行两个后续请求,您的请求将始终从 bean 的同一实例提供。这意味着您可以在请求之间保持对话状态。在生命周期结束时,客户端调用 remove 方法并且 bean 被销毁/准备好进行垃圾回收。

When to use stateless or stateful?

这主要取决于您是否要保持 session 状态。例如,如果您有一个将两个数字相加并返回结果的方法,您可以使用无状态 bean,因为它是一次性操作。如果您再次使用其他数字调用此方法,您将不再对先前添加的结果感兴趣。

但是,例如,如果您想计算客户端完成的请求数,则必须使用有状态 bean。在这种情况下,了解客户端之前请求 bean 方法的频率很重要,因此您必须在 bean 中维护 session 状态(例如,使用变量)。如果您在此处使用无状态 bean,则每次都会从不同的 bean 为客户端的请求提供服务,这会弄乱您的结果。

关于jakarta-ee - 何时在无状态 session bean 上使用有状态 session bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18000431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com