首页 > 编程语言 > 详细

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

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!