10

How can I get a reference to the cacheManager object in the Shiro framework in any part of my application? For example, I want to remove the old user data that was cached during the removal of a user or updating its permission. Right now I am handling it following way

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);
        }
    }
Evaldas Buinauskas
  • 13,739
  • 11
  • 55
  • 107
Prakash Bisht
  • 226
  • 1
  • 10
  • What is wrong with what you are doing? Also, have you looked at the Singleton pattern? This problem is pretty much what it is for! – JoeG Jul 08 '16 at 18:48
  • You have to be careful with the singleton pattern. You're susceptible to concurrency issues with initialization if you do it lazily. – Kurtymckurt Jul 26 '16 at 14:45

1 Answers1

0

If this class is the only place you're utilizing the cache, you can hold a final reference to the cache. There's no use in calling to get the cache manager and caches over and over.

I would recommend doing it in the constructor if you know the cache manager is initialized at that point.

Kurtymckurt
  • 337
  • 2
  • 6