⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lrucachehandler.java

📁 这个weblogging 设计得比较精巧
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * Created on Jun 15, 2004 */package org.roller.presentation.pagecache.rollercache;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.roller.pojos.UserData;import org.roller.presentation.LanguageUtil;import org.roller.presentation.pagecache.FilterHandler;import org.roller.util.LRUCache;import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Set;import java.util.Timer;import java.util.TimerTask;import java.util.TreeMap;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.roller.config.RollerConfig;/** * Page cache implementation that uses a simple LRUCache. Can be configured  * using filter configuration parameters: * <ul> * <li><b>size</b>: number of pages to keep in cache. Once cache reaches * this size, each new cache entry will push out the LRU cache entry.</li> *  * <li><b>timeoutInterval</b>: interval to timeout pages in seconds * (default is 1800 seconds). Sites with a large number of users, and thus a  * lot of cache churn which makes this check unnecessary, may wish to  set this *  to -1 to disable timeout checking.</li> *  * <li><b>timeoutRatio</b>: portion of old pages to expire on timeout  * interval where 1.0 is 100% (default is 1.0). This only applies if the  * timeoutInterval is set to something other than -1.</li> * </ul>  * @author David M Johnson */public class LRUCacheHandler implements FilterHandler{    private static Log mLogger =         LogFactory.getFactory().getInstance(LRUCacheHandler.class);    private Map mPageCache = null;        private String mName = null;        /** Timeout interval: how often to run timeout task (default 30 mintes) */    private long mTimeoutInterval = 30 * 60 * 1000; // milliseconds        /** Timeout ratio: % of cache to expire on each timeout (default 1.0) */    private float mTimeoutRatio = 1.0F;        // Statistics    private int misses = 0;    private int hits = 0;        private final static String FILE_SEPARATOR = "/";    private final static char FILE_SEPARATOR_CHAR = FILE_SEPARATOR.charAt(0);    private final static short AVERAGE_KEY_LENGTH = 30;    private static final String m_strBase64Chars =         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";        public LRUCacheHandler(FilterConfig config)    {              mName = config.getFilterName();        mLogger.info("Initializing for: " + mName);                String cacheSize = RollerConfig.getProperty("cache.filter.page.size");        String cacheTimeout = RollerConfig.getProperty("cache.filter.page.timeout");                int size = 200;        try        {            size = Integer.parseInt(cacheSize);        }        catch (Exception e)        {            mLogger.warn(config.getFilterName()                 + "Can't read cache size parameter, using default...");        }        mLogger.info(mName + " size=" + size);        mPageCache = Collections.synchronizedMap(new LRUCache(size));        long intervalSeconds = mTimeoutInterval / 1000L;        try        {            mTimeoutInterval = 1000L * Long.parseLong(cacheTimeout);                        if (mTimeoutInterval == -1)            {                mLogger.info(config.getFilterName()                    + "timeoutInterval of -1: timeouts are disabled");            }            else if (mTimeoutInterval < (30 * 1000))            {                mTimeoutInterval = 30 * 1000;                mLogger.warn(config.getFilterName()                    + "timeoutInterval cannot be less than 30 seconds");            }        }        catch (Exception e)        {            mLogger.warn(config.getFilterName()                 + "Can't read timeoutInterval parameter, disabling timeout.");            mTimeoutInterval = -1;        }        mLogger.info(mName + " timeoutInterval=" + intervalSeconds);                try        {            mTimeoutRatio = Float.parseFloat(                config.getInitParameter("timeoutRatio"));        }        catch (Exception e)        {            mLogger.warn(config.getFilterName()                 + "Can't read timeoutRatio parameter, using default...");        }        mLogger.info(mName + " timeoutRatio=" + mTimeoutRatio);                if (mTimeoutInterval != -1 && mTimeoutRatio != 0.0)        {            Timer timer = new Timer();                        timer.scheduleAtFixedRate(new TimerTask() {                public void run() {                    timeoutCache();                }            }, mTimeoutInterval, mTimeoutInterval);                }    }        /**     * @see org.roller.presentation.pagecache.FilterHandler#destroy()     */    public void destroy()    {    }    /**     * @see org.roller.presentation.pagecache.FilterHandler#doFilter(     *      javax.servlet.ServletRequest, javax.servlet.ServletResponse,     *      javax.servlet.FilterChain)     */    public void doFilter(ServletRequest req, ServletResponse res,                    FilterChain chain) throws ServletException, IOException    {        HttpServletRequest request = (HttpServletRequest) req;        HttpServletResponse response = (HttpServletResponse) res;        // get locale        Locale locale = LanguageUtil.getViewLocale(request);                // generate language-sensitive cache-key        String generatedKey = null;        if (locale != null)        {            generatedKey = generateEntryKey(null,                       request, 1, locale.getLanguage());        }        else        {            generatedKey = generateEntryKey(null,                       request, 1, null);        }                // Add authenticated user name, if there is one, to cache key        java.security.Principal prince = request.getUserPrincipal();                StringBuffer keyb = new StringBuffer();        keyb.append(generatedKey);        if (prince != null)        {            keyb.append("_");            keyb.append(prince);        }        String key = keyb.toString();                        ResponseContent respContent = (ResponseContent)getFromCache(key);        if (respContent == null)         {            try            {                CacheHttpServletResponseWrapper cacheResponse =                     new CacheHttpServletResponseWrapper(response);                chain.doFilter(request, cacheResponse);                                // Store as the cache content the result of the response                // if no exception was noted by content generator.                if (request.getAttribute("DisplayException") == null)                {                    ResponseContent rc = cacheResponse.getContent();                    putToCache(key, rc);                }                else                {                    StringBuffer sb = new StringBuffer();                    sb.append("Display exception, cache, key=");                    sb.append(key);                    mLogger.error(sb.toString());                }            }            catch (java.net.SocketException se)            {                // ignore socket exceptions            }            catch (Exception e)            {                // something unexpected and bad happened                StringBuffer sb = new StringBuffer();                sb.append("Error rendering page, key=");                sb.append(key);                mLogger.error(sb.toString());            }                   }        else        {            try            {                respContent.writeTo(response);            }            catch (java.net.SocketException se)            {                // ignore socket exceptions

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -