如何使用Apache Shiro ehcache-terracotta获得所有活动会话?

时间:2016-01-24 09:32:40

标签: ehcache shiro terracotta

在我的maven应用程序中,我想提供的是,如果用户登录新帐户,则另一个已经打开的帐户将被注销。我正在使用Apache shiro,ehcache和terracotta。 我想让所有活动会话检查该用户是否先前已登录。我可以使用Hazelcast(这可以)从所有服务器获取用户及其会话ID,但我无法进行会话(因为它不可序列化)

我在项目中使用群集服务器。服务器具有相同的IP地址,但它们的端口不同。 x.x.x.x:7002 - > server1, x.x.x.x:7003 - > server2 如何在ehcache配置文件中定义端口? 我怎么能用赤土陶器从那个港口拿走所有活动的会话?

请帮忙

ehcache.xml中:

<ehcache>
<terracottaConfig url="x.x.x.x:9510"/>

<diskStore path="java.io.tmpdir/shiro-ehcache"/>
<defaultCache
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="120"
    timeToLiveSeconds="120"
    overflowToDisk="false"
    diskPersistent="false"
    diskExpiryThreadIntervalSeconds="120">
    <!-- <terracotta/>-->
</defaultCache>
<cache name="myactiveSessionCache"
       maxElementsInMemory="10000"
       eternal="true"
       timeToLiveSeconds="0"
       timeToIdleSeconds="0"
       diskPersistent="false"
       overflowToDisk="false"
       diskExpiryThreadIntervalSeconds="600">
    <!-- <terracotta/>-->
</cache>
<!-- Add more cache entries as desired, for example,
Realm authc/authz caching: -->
</ehcache>

shiro.ini:

sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager.sessionDAO = $sessionDAO
cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager .cacheManagerConfigFile = classpath:ehcache.xml
securityManager.cacheManager = $cacheManager 
securityManager.sessionManager = $sessionManager

Login.java:

User newuser = ..//get from db with username and password
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject currentUser = new Subject.Builder().buildSubject();
token.setRememberMe(true);
currentUser = getSubject();
currentUser.login(token);

//at here, i take all active users and their's session id with Hazelcast. 
//and check that is 'newuser' in all active users list?
if (!activeuserList.containsKey(newuser)) {
    activeuserList.put(newuser, currentUser.getSession().getId());
} else {
    Serializable s = activeuserList.get(newuser);
    isSessionActive(s);
}
}

...
//check -- is session active?
public void isSessionActive(Serializable s) {
DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager)   SecurityUtils.getSecurityManager();
DefaultWebSessionManager sessionManager = (DefaultWebSessionManager) securityManager.getSessionManager();
EnterpriseCacheSessionDAO sessionDao = (EnterpriseCacheSessionDAO) sessionManager.getSessionDAO();
Cache<Serializable, Session> activeSessionsCache = sessionDao.getActiveSessionsCache();
if (activeSessionsCache.keys().contains(s)) {
        //previous session is closed.
        activeuserList.remove(newuser);
        activeSessionsCache.get(s).stop();
        //new session id is added to list
        activeuserList.put(newuser, currentUser.getSession().getId());
    }
}

0 个答案:

没有答案