您的足迹:首页 > JAVA >shiro删除缓存

shiro删除缓存

项目中用到shiro管理权限,当角色的权限改变后,要立刻刷新用户的权限,这样需要通过删除对应用户的cache来刷新权限

 

import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.youngpioneers.memory.admin.service.account.ShiroDbRealm.ShiroUser;
@Component
public class ShiroAuthorizationHelper {

 /**
  * 
  */
 @Autowired
 private  EhCacheManager ehCacheManager;
 
 //private static Logger log = LoggerFactory.getLogger(ShiroAuthorizationHelper.class);
 
 
 /**
  * 清除用户的授权信息
  * @param username
  */
 public  void clearAuthorizationInfo(String username){
  

  Cache<Object, Object> cache = ehCacheManager.getCache(ShiroDbRealm.class.getName()+".authorizationCache");
     //cache.remove(username);
  Set<Object> keys=cache.keys();
  Iterator<Object> it=keys.iterator();
  System.out.println(keys);
  while(it.hasNext()){
   Object key=it.next();
   System.out.println(key.getClass());
   if(username.equals(key.toString())){
      cache.remove(key);
   }
  }
  //System.out.println(keys.contains(username));
  //System.out.println(ss);
 
 }
 
 /**
  * 清除当前用户的授权信息
  */
 public  void clearAuthorizationInfo(){
  if(SecurityUtils.getSubject().isAuthenticated()){
   clearAuthorizationInfo(((ShiroUser)SecurityUtils.getSubject().getPrincipal()).username);
  }
 }
 
 /**清除session(认证信息)
  * @param JSESSIONID
  */
 public  void clearAuthenticationInfo(Serializable JSESSIONID){
  
  //shiro-activeSessionCache 为shiro自义cache名,该名在org.apache.shiro.session.mgt.eis.CachingSessionDAO抽象类中定义
  //如果要改变此名,可以将名称注入到sessionDao中,例如注入到CachingSessionDAO的子类EnterpriseCacheSessionDAO类中
  Cache<Object, Object> cache = ehCacheManager.getCache("shiro-activeSessionCache");
  cache.remove(JSESSIONID);
 }

 public EhCacheManager getEhCacheManager() {
  return ehCacheManager;
 }

 public void setEhCacheManager(EhCacheManager ehCacheManager) {
  this.ehCacheManager = ehCacheManager;
 }

 
 
 
}

 

从缓存的管理器中去获取缓存,然后删除对应的用户名的缓存,这样就可以更新权限了

本博客所有文章如无特别注明均为原创。作者:小天复制或转载请以超链接形式注明转自 钟天才的博客
原文地址《shiro删除缓存

相关推荐

网友评论(0)