如何在应用程序的任何部分从shiro框架获取cacheManager

Pra*_*sht 9 java shiro

如何在我的应用程序的任何部分中获取Shiro框架中的cacheManager对象的引用?例如,我想删除在删除用户或更新其权限期间缓存的旧用户数据.现在我按照以下方式处理它

public void cleanUserCache(final String userName) {
        final EmbeddedCacheManager embeddedCacheManager = securityRealmsProducer.getEmbeddedCacheManger();
        final Cache<Object, Object> authenticationCache = embeddedCacheManager.getCache("JPA-Auth-Realm.authenticationCache");
        final Cache<Object, Object> authrizationCache = embeddedCacheManager.getCache("JPA-Auth-Realm.authorizationCache");
        final Object userAuthenticationInfo = authenticationCache.get(userName);
        if (userAuthenticationInfo != null) {
            authenticationCache.remove(userName);
            final SimpleAuthenticationInfo principle = (SimpleAuthenticationInfo) userAuthenticationInfo;
            final SimplePrincipalCollection simple = (SimplePrincipalCollection) principle.getPrincipals();
            authorizationCache.remove(simple);
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 0

如果此类是您使用缓存的唯一位置,则您可以保存对缓存的最终引用。一遍又一遍地调用获取缓存管理器和缓存是没有用的。

如果您知道缓存管理器此时已初始化,我建议在构造函数中执行此操作。