要想使用 java 的本地缓存,可以考虑用 ehcache,或者 guava。

guava 更高端一点,可以自动定时刷新。我选择了 ehcache。

在 spring 中是集成了 ehcache 的。要使用 ehcache 的话,只需要下面几步:

当然需要首先引入 ehcache 相关的 jar 包。可以采用配置 pom 文件使用 maven 依赖的方式。

一、在 spring 的 applicationContext.xml 配置文件中配置好 ehcache 相关的 bean

    <!-- ehcache -->
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="spring/ehcache.xml"/>
</bean>
<bean id="manager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
</bean>

二、配置好 ehcache.xml

<?xml version="1.0" encoding="gbk"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">
<diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="30" timeToLiveSeconds="30" overflowToDisk="false"/>
<!--
配置自定义缓存
maxElementsInMemory:缓存中允许创建的最大对象数
eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,
两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,
如果该值是 0 就意味着元素可以停顿无穷长的时间。
timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,
这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
overflowToDisk:内存不足时,是否启用磁盘缓存。
memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。
-->
<cache name="TerritoryCache"
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="900"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LFU" /> </ehcache>

三、具体类中使用 CacheManager

@Component
public class TerritoryRangeCache {
@Autowired
EhCacheCacheManager manager; @Autowired
TerritoryRangeDao territoryRangeDao; Cache cache; public Object getAllTerritorRanges(String key) {

      cache = manager.getCacheManager().getCache("TerritoryCache");

        Object value = cache.get(key);
if (value == null) {
cache.putIfAbsent(new Element(key, territoryRangeDao.selectAll()));
return cache.get(key).getObjectValue();
}
return cache.get(key).getObjectKey();
}
}

其实具体类中使用注入的 EhCacheCacheManager 是 spring 自己封装过了的 CacheManager。要想获取引入的 ehCache 包里面的 CacheManager 的话,需要把spring 包装过的EhCacheCacheManager通过 getManager 拿出来。我们来看先EhCacheCacheManager的源码:

public class EhCacheCacheManager extends AbstractTransactionSupportingCacheManager {

    private net.sf.ehcache.CacheManager cacheManager;

    /**
* Create a new EhCacheCacheManager, setting the target EhCache CacheManager
* through the {@link #setCacheManager} bean property.
*/
public EhCacheCacheManager() {
} /**
* Create a new EhCacheCacheManager for the given backing EhCache CacheManager.
* @param cacheManager the backing EhCache {@link net.sf.ehcache.CacheManager}
*/
public EhCacheCacheManager(net.sf.ehcache.CacheManager cacheManager) {
this.cacheManager = cacheManager;
} /**
* Set the backing EhCache {@link net.sf.ehcache.CacheManager}.
*/
public void setCacheManager(net.sf.ehcache.CacheManager cacheManager) {
this.cacheManager = cacheManager;
} /**
* Return the backing EhCache {@link net.sf.ehcache.CacheManager}.
*/
public net.sf.ehcache.CacheManager getCacheManager() {
return this.cacheManager;
}
……
}

四、ehcaceh 的定时刷新,可以自己写一个方法,来更新缓存中的数据:

  @Scheduled(cron = " ")
@PostConstruct
public void refreshAll() {
cache = manager.getCacheManager().getCache("key");
getAllTerritorRanges("territory_range");
}

可以加上上面的方法,来通过 cron 表达式中传入的参数来定时刷新缓存中的数据。

关于@PostConstruct的使用以及含义,会在我的另一篇博文中介绍~。可以先看下这个注解的源码:

package javax.annotation;

import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*; /**
* The PostConstruct annotation is used on a method that needs to be executed
* after dependency injection is done to perform any initialization. This
* method MUST be invoked before the class is put into service. This
* annotation MUST be supported on all classes that support dependency
* injection. The method annotated with PostConstruct MUST be invoked even
* if the class does not request any resources to be injected. Only one
* method can be annotated with this annotation. The method on which the
* PostConstruct annotation is applied MUST fulfill all of the following
* criteria -
- The method MUST NOT have any parameters except in the case of EJB
* interceptors in which case it takes an InvocationC ontext object as
* defined by the EJB specification.
* - The return type of the method MUST be void.
* - The method MUST NOT throw a checked exception.
* - The method on which PostConstruct is applied MAY be public, protected,
* package private or private.
* - The method MUST NOT be static except for the application client.
* - The method MAY be final.
* - If the method throws an unchecked exception the class MUST NOT be put into
* service except in the case of EJBs where the EJB can handle exceptions and
* even recover from them.
* @since Common Annotations 1.0
* @see javax.annotation.PreDestroy
* @see javax.annotation.Resource
*/
@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}

看注释就能看懂吧~

ehcache 使用笔记的更多相关文章

  1. SpringBoot整合EHcache学习笔记

    为了提高系统的运行效率,引入缓存机制,减少数据库访问和磁盘IO.下面说明一下ehcache和SpringBoot整合配置 前言介绍 EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特 ...

  2. Hibernate学习笔记之EHCache的配置

    Hibernate默认二级缓存是不启动的,启动二级缓存(以EHCache为例)需要以下步骤: 1.添加相关的包: Ehcache.jar和commons-logging.jar,如果hibernate ...

  3. 我的ehcache笔记

    我的EhcacheUtils类: package com.shinho.bi.utils; import org.ehcache.CacheManager; import org.ehcache.co ...

  4. MyBatis笔记——EhCache二级缓存

    介绍 ehcache是一个分布式缓存框架. 我们系统为了提高系统并发,性能.一般对系统进行分布式部署(集群部署方式)  不使用分布缓存,缓存的数据在各各服务单独存储,不方便系统开发.所以要使用分布式缓 ...

  5. ehcache的学习笔记(一)

    学习ehcache文档: 介绍:Ehcache是一个开源的项目,用来提高性能的基于标准化的缓存,无需使用数据库,简化了可扩展性.他是最广泛使用的基于java的缓存,因为他是强壮的,被证实的,功能全面的 ...

  6. SpringBoot学习笔记(10)-----SpringBoot中使用Redis/Mongodb和缓存Ehcache缓存和redis缓存

    1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...

  7. [原创]java WEB学习笔记93:Hibernate学习之路---Hibernate 缓存介绍,缓存级别,使用二级缓存的情况,二级缓存的架构集合缓存,二级缓存的并发策略,实现步骤,集合缓存,查询缓存,时间戳缓存

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  8. EhCache 分布式缓存/缓存集群

    开发环境: System:Windows JavaEE Server:tomcat5.0.2.8.tomcat6 JavaSDK: jdk6+ IDE:eclipse.MyEclipse 6.6 开发 ...

  9. Java学习笔记4

    Java学习笔记4 1. JDK.JRE和JVM分别是什么,区别是什么? 答: ①.JDK 是整个Java的核心,包括了Java运行环境.Java工具和Java基础类库. ②.JRE(Java Run ...

随机推荐

  1. 小谈JavaScript中this的用法

    "this"关键字是JavaScript中广泛应用的一种特性,但它经常也是这门语言中最容易混淆和误解的特性.那么"this"的实际意义是什么?它是如何求值的? ...

  2. Nancy简单实战之NancyMusicStore(六):写在最后

    前言 由于公司搬家后,住的地方离上班的地方远了N倍,以前是走路十多分钟就可以到公司的,上班时间也从9:00提早到8:30 现在每天上班都是先坐公交,然后再坐地铁,在这段路上比较浪费时间而且每天都是要6 ...

  3. HDU3652(数位dp)

    A - B-number Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Descri ...

  4. C++从string中删除所有的某个特定字符

    C++中要从string中删除所有某个特定字符, 可用如下代码 str.erase(std::remove(str.begin(), str.end(), 'a'), str.end()); 其中, ...

  5. 关于Coursera上的斯坦福机器学习课程的编程作业提交问题

    学习Coursera上的斯坦福机器学习课程的时候,需要向其服务器提交编程作业,我遇到如下问题: 'Submission failed: unexpected error: urlread: Peer ...

  6. 从jvm的角度来看单例模式

    最近在看jvm,发现随着自己对jvm底层的了解,现在对java代码可以说是有了全新的认识.今天就从jvm的角度来看一看以前自以为很了解的单例模式. 了解单例模式的人都知道,单例模式有两种:" ...

  7. 《JAVASCRIPT高级程序设计》DOM扩展

    虽然DOM为XML及HTML文档交互制定了一系列的API,但仍然有几个规范对标准的DOM进行了扩展.这些扩展中,有很多是浏览器专有的,但后来成了事实标准,于是其他浏览器也提供了相同的实现:浏览器开发商 ...

  8. ArcGIS制图表达Representation实战篇2-河流渐变与符号旋转

    ArcGIS制图表达Representation实战篇2-河流渐变与符号旋转 by 李远祥 上一章节主要是从实战中使用规则和几何效果,如何分解制图规则.本章主要还是通过一些特殊要求如河流线宽渐变和符号 ...

  9. 百度富文本编辑器ueditor在jsp中的使用(ssm框架中的应用)

    折腾了一下午终于把百度富文本编辑器ueditor搞定了!   项目地址:https://github.com/724888/lightnote_new     首先我参考了一个ueditor的demo ...

  10. 读书笔记 effective c++ Item 6 如果你不想使用编译器自动生成的函数,你需要明确拒绝

    问题描述-阻止对象的拷贝 现实生活中的房产中介卖房子,一个服务于这个中介的软件系统很自然的会有一个表示要被销售的房屋的类: class HomeForSale { ... }; 每个房产中介会立刻指出 ...