简体   繁体   中英

spring boot+ shiro authorizationCache.clear NullPointerException

<dependency>
            <groupId>org.crazycake</groupId>
            <artifactId>shiro-redis</artifactId>
             <version>3.1.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>shiro-core</artifactId>
                    <groupId>org.apache.shiro</groupId>
                </exclusion>
            </exclusions>
        </dependency>
public class UserRealm extends AuthorizingRealm {
   
    public void clearAllCachedAuthorizationInfo() {
        Cache<Object, AuthorizationInfo> authorizationCache = getAuthorizationCache();
        //authorizationCache is null
        authorizationCache.clear();
    }
}
 @Bean
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(RedisConfigurer.IP);
        redisManager.setPort(RedisConfigurer.PORT);
        redisManager.setPassword(RedisConfigurer.PASSWORD);
        redisManager.setTimeout(2000);
        redisManager.setDatabase(ShiroCache.DB_INDEX);
        return redisManager;
    }
  @Bean
    public RedisCacheManager redisCacheManager(RedisManager redisManager) {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager);
        return redisCacheManager;
    }

When I update the permission information and want to remove all old user authorization information, call the method getAuthorizationCache() result null !

What am I doing wrong?

First of all, it seems like caching is not mandatory, from what I understand of the AuthorizingRealm JavaDoc:

The AuthorizationInfo values returned from this method are cached for efficient reuse if caching is enabled.

To enable caching, also from the AuthorizingRealm JavaDoc:

Caching is enabled automatically when an {@link #setAuthorizationCache authorizationCache} instance has been explicitly configured, or if a #setCacheManager cacheManager has been configured, which will be used to lazily create the authorizationCache as needed.

So if a cache manager has been configured but no need for a cache has arisen, the cache instance may also be null. Thus I would implement a check of the result from getAuthoriationCache() to see if it is not null before trying to call the clear() method on the cache.

 public void clearAllCachedAuthorizationInfo() {
    Cache<Object, AuthorizationInfo> authorizationCache = getAuthorizationCache();
    if (authorizationCache != null) {
        authorizationCache.clear();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM