---
title: "spring +ehcache 持久化数据，重启恢复"
author: "greemranqq"
date: "2014-12-08T17:24:22Z"
tags: ["Spring", "contextdestroyed", "ehcache"]
categories: ["互联网"]
slug: "spring-ehcache"
draft: false
lastmod: "2014-12-08T17:24:22Z"
id: 2164243
url: "https://greemranqq.iteye.com/blog/2164243"
---

今天有个需求，要求用户登录的时候展示一些信息，但是这些信息跨系统反复调用，比较慢，因此做数据缓存。有些系统不大，就ehcache 就可以了。但是因为有个子系统发布比较平凡，不希望重启之后缓存数据丢失，因此做持久化处理。框架是jfinal+spring+ehcache ，东西没啥区别。

         下面是遇到的几个问题：

         1.同一个类里面，A方法  上面加上注解 缓存，然后B方法 去调用，缓存无效..

            解决：隔离开，A B方法放两个不同的类里面。

 

          2.持久化的数据无法恢复。

             解决：ehcache 和其他缓存类似，需要flush 或者shutdown 才会持久化到硬盘。

             会生成.data 的数据文件和 .index 的索引文件，方便重启恢复。

 

         3.想利用spring 的注解，不想手动shutdown ，因此web.xml 配置listener 监听，在销毁的时候进行shutdown,这里利用ehcache 的监听.

        

```
    <!-- ehcache 磁盘缓存 监控，持久化恢复 -->
    <listener>
        <listener-class>net.sf.ehcache.constructs.web.ShutdownListener</listener-class>
    </listener>
```

    源码也就几句话：

 

   

```
 /**
     * Notification that the servlet context is about to be shut down.
     * <p/>
     * Shuts down all cache managers known to {@link CacheManager#ALL_CACHE_MANAGERS}
     *
     * @param servletContextEvent
     */
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        List knownCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Shutting down " + knownCacheManagers.size() + " CacheManagers.");
        }
        while (!knownCacheManagers.isEmpty()) {
            // 关闭的时候 刷到磁盘
            ((CacheManager) CacheManager.ALL_CACHE_MANAGERS.get(0)).shutdown();
        }
    }
```

   

 

       4.IDE 工具是idea ，估计eclipse 差不多，点击红色按钮和重启按钮的时候，监听无法执行，猜测执行的类似kill -9 直接杀死进程的方法，而不是kill -15 比较安全的关闭。

      解决：由于idea 集成了maven 很简单，名字添加一个jetty:stop 命令，就行了，tomcat 也有命令，看服务而已。

 

       小结：

        1.这里记录一下经验，和一些零碎的小问题

        2.ehcache 其实挺强大的，特别是2.8 以后的版本，更新挺多的，使用比较方便

        3.使用服务器的时候，有些持久化缓存（包括redies），尽量用正常的方式关闭或者重启，别太暴力~。~