OSCache工具类

<% @ taglib uri = " oscache "  prefix = " cache " %>

< cache:flush group = " device_types "  scope = " application "   />
但是有时需要在java代码中刷新缓存,以下这个OSCacheUtil类可以工作,但是只能在webwork环境内调用:

import  javax.servlet.jsp.PageContext;

import  org.apache.log4j.Logger;
import  com.opensymphony.oscache.base.Cache;
import  com.opensymphony.oscache.web.ServletCacheAdministrator;
import  com.opensymphony.webwork.ServletActionContext;

/**
 * osCache缓存工具类.
 * 只能在webwork环境内调用
 *
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: </p>
 * 
@author 杨杰荣
 * 
@version 1.0
 
*/

public   class  OSCacheUtil
{
  
private static final Logger log = Logger.getLogger( OSCacheUtil.class );

  
public static final int ALL_SCOPE = 0;
  
public static final int SESSION_SCOPE = PageContext.SESSION_SCOPE;
  
public static final int APPLICATION_SCOPE = PageContext.APPLICATION_SCOPE;

  
private static ServletCacheAdministrator admin = null;

  
private OSCacheUtil()
  
{
  }


  
/**
   * 刷新osCache组
   * 
@param group Cache组名
   * 
@param cacheScope Cache范围,只能是SESSION_SCOPE或APPLICATION_SCOPE
   
*/

  
public static void flushGroup( String group, int cacheScope )
  
{
    initCacheAdmin();

    
if ( cacheScope == SESSION_SCOPE || cacheScope == APPLICATION_SCOPE )
    
{
      Cache cache 
= admin.getCache( ServletActionContext.getRequest(),
                                    cacheScope );
      cache.flushGroup( group );
    }

    
else
    
{
      log.warn( 
"A cache group was specified for flushing, but the scope wasn't supplied or was invalid" );
    }

  }


  
/**
   * 刷新osCache中的某个key'
   * 
@param key String
   * 
@param cacheScope Cache范围,只能是SESSION_SCOPE或APPLICATION_SCOPE
   
*/

  
public static void flushKey( String key, int cacheScope )
  
{
    initCacheAdmin();

    
if ( cacheScope == SESSION_SCOPE || cacheScope == APPLICATION_SCOPE )
    
{
      String actualKey 
= admin.generateEntryKey(
          key, ServletActionContext.getRequest(), cacheScope, 
null );

      Cache cache 
= admin.getCache( ServletActionContext.getRequest(), cacheScope );
      cache.flushEntry( actualKey );
    }

    
else
    
{
      log.warn( 
"A cache key was specified for flushing, but the scope wasn't supplied or was invalid" );
    }

  }


  
/**
   * 刷新所有的osCache
   * 
@param cacheScope Cache范围,可以是SESSION_SCOPE,APPLICATION_SCOPE,ALL_SCOPE
   
*/

  
public static void flushAll( int cacheScope )
  
{
    initCacheAdmin();

    
if ( cacheScope == SESSION_SCOPE || cacheScope == APPLICATION_SCOPE )
    
{
      admin.setFlushTime( cacheScope );
    }

    
else
    
{
      admin.flushAll();
    }

  }



  
private static void initCacheAdmin()
  
{
    
if ( admin == null )
    
{
      admin 
= ServletCacheAdministrator.getInstance( ServletActionContext.
          getServletContext() );
    }

  }

官网http://www.opensymphony.com/oscache/api/

猜你喜欢

转载自2374458997.iteye.com/blog/1815045