java缓存实现

一、在开发项目工程时,经常会遇到保存某些值放到系统的cache中,现用Cache.java和CacheManager.java来管理。具体代码分别如下:
public class Cache {
        private String key;
        private Object value;
        private long timeOut;
        private boolean expired;
        public Cache() {
                super();
        }
               
        public Cache(String key, String value, long timeOut, boolean expired) {
                this.key = key;
                this.value = value;
                this.timeOut = timeOut;
                this.expired = expired;
        }

        public String getKey() {
                return key;
        }

        public long getTimeOut() {
                return timeOut;
        }

        public Object getValue() {
                return value;
        }

        public void setKey(String string) {
                key = string;
        }

        public void setTimeOut(long l) {
                timeOut = l;
        }

        public void setValue(Object object) {
                value = object;
        }

        public boolean isExpired() {
                return expired;
        }

        public void setExpired(boolean b) {
                expired = b;
        }
}

另外一个类:
import java.util.Date;
import java.util.HashMap;

public class CacheManager {
        private static HashMap cacheMap = new HashMap();

        /**
         * This class is singleton so private constructor is used.
         */
        private CacheManager() {
                super();
        }

        /**
         * returns cache item from hashmap
         * @param key
         * @return Cache
         */
        private synchronized static Cache getCache(String key) {
                return (Cache)cacheMap.get(key);
        }

        /**
         * Looks at the hashmap if a cache item exists or not
         * @param key
         * @return Cache
         */
        private synchronized static boolean hasCache(String key) {
                return cacheMap.containsKey(key);
        }

        /**
         * Invalidates all cache
         */
        public synchronized static void invalidateAll() {
                cacheMap.clear();
        }

        /**
         * Invalidates a single cache item
         * @param key
         */
        public synchronized static void invalidate(String key) {
                cacheMap.remove(key);
        }

        /**
         * Adds new item to cache hashmap
         * @param key
         * @return Cache
         */
        private synchronized static void putCache(String key, Cache object) {
           cacheMap.put(key, object);
        }

        /**
         * Reads a cache item's content
         * @param key
         * @return
         */
        public static Cache getContent(String key) {
                 if (hasCache(key)) {
                        Cache cache = getCache(key);
                        if (cacheExpired(cache)) {
                                cache.setExpired(true);
                        }
                        return cache;
                 } else {
                         return null;
                 }
        }

        /**
         *
         * @param key
         * @param content
         * @param ttl
         */
        public static void putContent(String key, Object content, long ttl) {
                Cache cache = new Cache();
                cache.setKey(key);
                cache.setValue(content);
                cache.setTimeOut(ttl + new Date().getTime());
                cache.setExpired(false);
                putCache(key, cache);
        }
       
        /** @modelguid {172828D6-3AB2-46C4-96E2-E72B34264031} */
        private static boolean cacheExpired(Cache cache) {
                if (cache == null) {
                        return false;
                }
                long milisNow = new Date().getTime();
                long milisExpire = cache.getTimeOut();
                if (milisExpire < 0) {                // Cache never expires
                        return false;
                } else if (milisNow >= milisExpire) {
                        return true;
                } else {
                        return false;
                }
        }

}

二、在web应用中启动服务加载缓存,具体代码如下
新建个servlet,保证启动服务时运行,加载缓存类
public class CacheServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public CacheServlet() {
super();
CacheManager.invalidateAll();
CacheManager.putContent("a", "a", 0);
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}

在web.xml加入配置
<servlet>
    <servlet-name>CacheServlet</servlet-name>
    <servlet-class>com.cache.CacheServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
</servlet>
加入load-on-startup为了让启动时初始化class,不需要加入mapping

这样就可以启动时候加载缓存类,内存中保存着CacheManager

你可能感兴趣的:(java,Web,cache,servlet,配置管理)