在src下创建ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="es">
    <diskStore path="java.io.tmpdir"/>
    <!-- name属性是根据需要自行取名 -->
    <!-- cache节点可以有多个 -->
    <cache name="passwordRetryCache" 
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <cache name="code"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
</ehcache>
    <!--  缓存  属性-->  
    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">    
        <property name="configLocation"  value="classpath:ehcache.xml"/>   
    </bean>   
    <!-- 支持缓存注解 -->  
    <cache:annotation-driven cache-manager="cacheManager" />  
    <!-- 默认是cacheManager -->  
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">    
        <property name="cacheManager"  ref="cacheManagerFactory"/>    
    </bean> 注意:要导入spring-context-support包,加入相应的命名空间
例如,在service实现类中使用注解注入
@Service
public class OauthServiceImpl implements OauthService{
    private Cache cache;
    //构造方法,使用注入方式
    @Autowired
    public OauthServiceImpl(CacheManager cacheManager){
        //根据key获取对应的cache,这里的key就是配置文件中的name属性
        this.cache = cacheManager.getCache("code");
    }
    @Override
    public void addAuthCode(String authCode, String username) {
        cache.put(authCode, username);
    }
    @Override
    public String getUsernameByAuthCode(String authCode) {
        return (String) cache.get(authCode).get();
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
spring学习笔记(26)——spring整合ehcache
原文地址:http://blog.csdn.net/u010837612/article/details/48026513