---
title: "在spring中使用Ehcache"
author: "Inmethetiger"
date: "2014-06-18T16:07:15Z"
tags: ["Cache", "Spring"]
categories: ["编程语言"]
slug: "spring-ehcache"
draft: false
lastmod: "2014-06-18T16:08:00Z"
id: 2082213
url: "https://inmethetiger.iteye.com/blog/2082213"
---

前提：

使用环境：详细页面

依赖包：

        &lt;dependency&gt;

            &lt;groupId&gt;com.googlecode.ehcache-spring-annotations&lt;/groupId&gt;

            &lt;artifactId&gt;ehcache-spring-annotations&lt;/artifactId&gt;

            &lt;version&gt;1.2.0&lt;/version&gt;

            &lt;type&gt;jar&lt;/type&gt;

            &lt;scope&gt;compile&lt;/scope&gt;

        &lt;/dependency&gt;

        &lt;dependency&gt;

            &lt;groupId&gt;net.sf.ehcache&lt;/groupId&gt;

            &lt;artifactId&gt;ehcache-core&lt;/artifactId&gt;

            &lt;version&gt;2.6.6&lt;/version&gt;

            &lt;type&gt;jar&lt;/type&gt;

            &lt;scope&gt;compile&lt;/scope&gt;

        &lt;/dependency&gt;

        &lt;dependency&gt;

            &lt;groupId&gt;com.google.guava&lt;/groupId&gt;

            &lt;artifactId&gt;guava&lt;/artifactId&gt;

            &lt;version&gt;r09&lt;/version&gt;

            &lt;type&gt;jar&lt;/type&gt;

            &lt;scope&gt;compile&lt;/scope&gt;

        &lt;/dependency&gt;

 

使用方法：

    在applicationContext中：

    &lt;cache:annotation-driven cache-manager="cacheManager"

        proxy-target-class="false" mode="proxy" /&gt;

    &lt;!-- &lt;aop:config proxy-target-class="true"&gt;&lt;/aop:config&gt; --&gt;

    &lt;!-- cacheManager工厂类 --&gt;

    &lt;bean id="cacheManagerFactory"

        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"&gt;

        &lt;property name="configLocation"&gt;

            &lt;value&gt;classpath:ehcache.xml&lt;/value&gt;

        &lt;/property&gt;

        &lt;property name="shared"&gt;

            &lt;value&gt;false&lt;/value&gt;

        &lt;/property&gt;

    &lt;/bean&gt;

    &lt;!-- 声明cacheManager --&gt;

    &lt;bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"&gt;

        &lt;property name="cacheManager" ref="cacheManagerFactory"&gt;&lt;/property&gt;

    &lt;/bean&gt;

2：在dao或者service中需要缓存的方法上加上

@Cacheable("items")

3：在ehcache.xml中加上2注解的cache

    &lt;!-- 详细页面 --&gt;

    &lt;cache name="items" maxElementsInMemory="100" maxElementsOnDisk="0"

        eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="100"&gt;

    &lt;/cache&gt;

4：需要改进的地方

        4.1：不放在内存中，而是放在硬盘上。前提是被缓存的内容以及相关类需要实现Serializable接口

    4.2：如果相关类中使用了list.subList则需要重新包装subList因为subList没有实现Serializable接口。不能序列化  .

    4.3：正常情况下，不能缓存所有内容。因为比如库存等，在更新的时候需要及时更新。