`
农村哥们
  • 浏览: 286882 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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
分享到:
评论
4 楼 zsw_it_eye 2013-12-25  
     
3 楼 charles751 2012-09-03  
集群部署环境下不适用。
2 楼 一江春水邀明月 2012-02-11  
推荐 http://www.source-code.biz/snippets/java/6.htm 用 LinkedHashMap 吧
1 楼 一江春水邀明月 2012-02-11  
貌似缺一个对Hashmap 中的过时对象清理的机制, 你这样很容易造成OOM 的。

而且即使你用Timer去遍历Hashmap 元素并做清理还是不能保证就不会OOM, 缓存不推荐用Hashmap 实现的。

相关推荐

    java 缓存的简单实现

    java缓存实现demo完整实例,很不错的资源,欢迎大家来下载学习。/** * 此函数接受一个对象列表,数目不定,opration:表是触发的事件 * eg:change;fnClear:表示初始化下拉框。var_args表示多个下拉框... */ ...

    java缓存实现与spring托管

    2. EHCACHE页面缓存的配置 5 2.1 EHCACHE的类层次模型 5 2.2环境搭建 6 2.3 EHCACHE配置文件中元素说明 8 2.4 在工程中单独使用 10 3. 在SPRING中运用EHCACHE 17 4. 分布式缓存集群环境配置 19 4.1 集群配置方式 19 ...

    Java利用ConcurrentHashMap实现本地缓存demo

    Java利用ConcurrentHashMap实现本地缓存demo; 基本功能有缓存有效期、缓存最大数、缓存存入记录、清理线程、过期算法删除缓存、LRU算法删除、获取缓存值等功能。 复制到本地项目的时候,记得改包路径哦~

    Java缓存框架Java缓存框架

    EhCache EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。 主要的特性有: 1. 快速. 2. 简单. 3. 多种缓存策略 4.... 提供Hibernate的缓存实现 10. 等等

    java 通过文件实现缓存

    java实现缓存可以通过读取本地文件的方式实现,改代码就是通过读取本地文件实现缓存的简单例子

    java简单的缓存池实现

    java缓存原理,简单的缓存池实现,java缓存原理,简单的缓存池实现,java缓存原理,简单的缓存池实现,java缓存原理,简单的缓存池实现。

    java map 实现缓存技术

    java map 缓存 //毫秒计算 this.timeOut = timeOut*1000;

    Java中LocalCache本地缓存实现代码

    本篇文章主要介绍了Java中LocalCache本地缓存实现代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    java Map实现的cache manager,定时清除缓存里面的值

    java Map实现的cache manager,定时清除缓存里面的值,使数据一致保持最新

    分页缓存

    分页缓存&lt;用java实现分页,并读取过程先读取缓存数据&gt;

    Java缓存技术的使用实例

    自己实现的Java缓存技术的实现实例代码,部署可以直接运行。。。

    Java中常用缓存Cache机制的实现

    主要介绍了Java中常用缓存Cache机制的实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    Java缓存框架 Ehcache.zip

    EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。 下图是 Ehcache 在应用程序中的位置: ... 提供Hibernate的缓存实现10. 等等 标签:缓存

    仿redis缓存Java版轻量级缓存组件LocalCache

    仿redis缓存Java版轻量级缓存组件LocalCache,基于JVM内存实现数据缓存及过期机制

    高速缓存实现源码

    运用java语言实现了高速缓存,并在实现了不用缓存的对比,1000个线程并发时相差十倍的时间,10000个线程时相差四十倍的时间。

    JAVA缓存概念体系及应用

    该压缩包中有一个WORD和一个PPT,WORD中介绍了通过单实例和简单LRU算法实现缓存。PPT中介绍了缓存体系,JVM内存模型,JCONSOLE监控工具的使用,Oscache缓存架构 Ehcache缓存架构 Memcached缓存架构 JiveCache缓存架构...

    DelayQueue延迟队列和Redis缓存实现订单自动取消功能

    java使用DelayQueue延迟队列和Redis缓存实现订单自动取消功能

    java手写本地缓存示例

    基于java的map和timer实现本地缓存及定时清理失效缓存的功能 本项目仅用于初学者学习使用 初学者可基于此项目初步了解缓存实现的基本原理 后期在项目中使用建议使用现成的缓存框架:redis、ehcache等

    JAVA缓存入门文档..Cache

    EHCache 的特点,系统要求及安装 是一个纯Java ,过程中(也可以理解成插入式)缓存实现

    Java实现的树以及包含树的内存缓存框架

    随手写了一个TreeNode,顺道实现了个对应的内存缓存框架,适用于数据量不大,更新也少但是反复要读的数据,比如模块信息/组织结构/频道栏目/权限等。 PS:Java是可以直接操作内存的,只是现在的框架整合让人退化了。...

Global site tag (gtag.js) - Google Analytics