何时在无状态会话 bean 上使用有状态会话 bean?

有状态会话 bean 定义如下:

状态会话 Bean 对象的状态由值组成 在有状态会话 bean 中,实例 变量表示唯一的客户端 bean 会话的状态 客户端与其 bean 进行交互(“会话”) ,这种状态通常是 叫做谈话状态。

无状态会话 bean 定义如下:

无状态会话 bean 不维护 当客户端调用 方法,bean 的实例变量可能包含 特定于该客户端的状态,但仅在 当方法完成时,特定于客户端的状态 不应保留。但是,客户端可以更改 实例变量,并保持此状态 转到下一次调用池无状态 bean 在方法调用期间,无状态 bean 的所有实例都是 等效,允许 EJB 容器将实例分配给任何 也就是说,应该应用无状态会话 bean 的状态 所有的客户。

与有状态会话 bean 相比,使用无状态会话 bean 的优点如下:

因为无状态会话 bean 可以支持多个客户端,所以它们可以 为需要大量数据的应用程序提供更好的可伸缩性 通常,应用程序需要较少的无状态会话 比有状态会话 bean 支持相同数量的 客户。

因此,我们想到的问题是什么时候应该使用有状态会话 bean?根据我对这个问题的天真理解,应该尽可能坚持使用无状态会话 bean。

应该在哪些候选项中使用有状态会话 bean? 有什么好的例子吗?

会话豆

83874 次浏览

First, you have to understand how the beans are created and handled on the server.

For stateless session beans the server can maintain a variable amount of instances in a pool. Each time a client requests such a stateless bean (e.g. through a method) a random instance is chosen to serve that request. That means if the client does two subsequent requests it is possible that two different instances of the stateless bean serve the requests. In fact, there is no conversational state between the two requests. Also if the client disappears, the stateless bean does not get destroyed and can serve the next request from another client.

On the other hand a stateful session bean is closely connected to the client. Each instance is created and bounded to a single client and serves only requests from that particular client. So happens that if you do two subsequent requests on a stateful bean, your request will be served always from the same instance of the bean. That means you can maintain a conversational state between the requests. At the end of the lifecycle, the client calls a remove method and the bean is being destroyed/ready for garbage collection.

When to use stateless or stateful?

That mainly depends on whether you want to maintain the conversational state. For example, if you have a method that adds up two numbers and return the result you use a stateless bean because it's a one-time operation. If you call this method a second time with other numbers you are not interested in the result of the previous addition anymore.

But if you want, for example, to count the number of requests a client has done, you have to use a stateful bean. In this scenario it is important to know how often the client has requested the bean method before, so you have to maintain a conversational state in the bean (e.g. with a variable). If you would use a stateless bean here, the request of the client would be served each time from a different bean, which messes up your results.

I think that the greatest example of using a Stateful session bean is for a Shopping Cart, where you store all products which user wants to buy.