EJB容器中的ThreadLocal(和Singleton) [英] ThreadLocal (and Singleton) in EJB Container

查看:176
本文介绍了EJB容器中的ThreadLocal(和Singleton)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个授权系统,它依赖于代表当前用户的对象。为了简化编程并提高性能,我想在用户登录后在ThreadLocal中保存这些对象。

I've written an authorization system which relies on objects representing the current user. To simplify programming and increase performance I want to hold those objects in a ThreadLocal after the user has logged in.

看起来像这样:

public class UserCache {

    private static final ThreadLocal<User> cache = new ThreadLocal<User>();

    public User getCurrentUser() {
        return cache.get();
    }

    public void setCurrentUser(User user) {
        cache.set(user);
    }

}

我读过静态元素使聚类成问题。如果我在每个群集节点上都有一个UserCache,那么它们都有自己的缓存对象与其他节点上的缓存对象不同步。对? UserCache 是单例的经典候选者,因为应用程序只需要它的一个实例。但据我所知,@ Singleton EJB在集群中具有相同的行为。

I've read that static elements make clustering problematic. If I had an UserCache on each cluster node, they all had their own cache object not synchronized with the cache objects on other nodes. Right? UserCache is a classic candidate for a singleton, because the application needs only a single instance of it. But as far as I know @Singleton EJBs have the same behaviour in a cluster.

那么如何使UserCache在EJB 3.1(Java EE 6)环境中可以集群化?

So what to do to make UserCache clusterable in an EJB 3.1 (Java EE 6) environment?

从答案中提取的解决方案:


  • 使用CDI的SessionScope(JSR 299)或

  • 使用Terracotta的JVM群集

推荐答案

由于您已经使用Java EE 6,因此使用CDI(上下文和依赖注入)甚至不会更容易。这将允许将用户信息放入会话范围,并在任何地方轻松注入。 CDI为您管理其余部分。

Since you're already on Java EE 6, wouldn't it even be a lot easier to use CDI (Contexts and Dependency Injection). This would allow to put the user info in the session scope, and inject it easily everywhere. CDI manages the rest for you.

这篇关于EJB容器中的ThreadLocal(和Singleton)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆