码迷,mamicode.com
首页 > 编程语言 > 详细

spring学习笔记(26)——spring整合ehcache

时间:2015-08-27 15:25:57      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:spring   缓存   

ehcache配置文件

在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>

spring配置文件中配置

    <!--  缓存  属性-->  
    <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

标签:spring   缓存   

原文地址:http://blog.csdn.net/u010837612/article/details/48026513

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!