鲁春利的工作笔记,谁说程序员不能有文艺范?


Ehcache是基于Java的开源cache,它提供了强大的缓存能力,并且易于和其他系统集成。

Ehcache is an open-source, standards-based cache for boosting performance, offloading
your database, and simplifying scalability. As a robust, proven, and full-featured
solution, it is today’s most widely used Java-based cache. You can use Ehcache as a
general-purpose cache or a second-level cache for Hibernate. You can additionally
integrate it with third-party products such as ColdFusion, Google App Engine, and
Spring.

Ehcache分为ehcache2和ehcache3:

Ehcache2地址为:http://www.ehcache.org

Ehcache3地址为:https://github.com/ehcache/ehcache3/releases

Ehcache3是ehcache版本演进过程中的里程碑,增加了Off-Heap 存储和 JSR107 兼容,并且将代码托管到 Github。

Ehcache2的Maven支持

<dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache</artifactId><version>2.10.0</version>
</dependency>

Ehcache3的Maven支持

<dependency><groupId>org.ehcache</groupId><artifactId>ehcache</artifactId><version>3.0.0.m4</version>
</dependency>

Ehcache支持声明式的配置和编程式的配置。

Ehcache的默认配置文件为:ehcache.xml(http://www.ehcache.org/ehcache.xml)

Ehcache的默认配置文件为ehcache-failsafe.xml(位于ehcache-2.10.0.jar包中),但在应用中一般会创建并使用ehcache.xml,在ehcache.xml中对配置参数重新定义。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"updateCheck="true" monitoring="autodetect"dynamicConfig="true"><!-- 指定磁盘存储的路径,会在该目录先创建.data和.index分别存储数据与索引 。可能的取值有:* user.home - User's home directory* user.dir - User's current working directory* java.io.tmpdir - Default temp file path* ehcache.disk.store.dir - A system property you would normally specify on the command linee.g. java -Dehcache.disk.store.dir=/u01/myapp/diskdir ...Subdirectories can be specified below the property e.g. java.io.tmpdir/one--><diskStore path="java.io.tmpdir"/><!-- Mandatory Default Cache configuration.--><defaultCachemaxEntriesLocalHeap="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"diskSpoolBufferSizeMB="30"maxEntriesLocalDisk="10000000"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"><persistence strategy="localTempSwap"/></defaultCache><!-- With the "localTempSwap" strategy, you can use maxEntriesLocalDisk ormaxBytesLocalDisk at either the Cache or CacheManager level to control thesize of the disk tier.When the persistence strategy is "none", all cache stays in memory (withno overflow to disk nor persistence on disk).--><!-- 自定义cache。name:自定义名称, 必须唯一。maxEntriesLocalHeap:Sets the maximum number of objects that will be created in memory.  0 = no limit.maxBytesLocalHeap:Defines how many bytes the cache may use from the VM's heap,<number>k|K|m|M|g|G。eternal:Sets whether elements are eternal. If eternal,  timeouts are ignored and the element is never expired.overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上。 diskPersistent: 是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。 timeToIdleSeconds: 对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。timeToLiveSeconds: 对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。    diskExpiryThreadIntervalSeconds: 对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。diskSpoolBufferSizeMB: DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。memoryStoreEvictionPolicy: 如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。 说明:overflowToDisk和diskPersistent、DiskStoreBootstrapCacheLoaderFactory是在2.5及之前版本拥有的参数;2.6及之后的版本建议使用<persistence>或<terracotta>来代替,参阅ehcache.xsd。<persistence strategy="localTempSwap"/>或<persistence strategy="none"/>--><cache name="invicmeCache"maxEntriesLocalHeap="500"eternal="false"overflowToDisk="true"diskPersistent="true"timeToIdleSeconds="300"timeToLiveSeconds="600"diskExpiryThreadIntervalSeconds="1"memoryStoreEvictionPolicy="LFU"></cache>
</ehcache>

所有ehcache的使用, 都是从 CacheManager开始的,有多种方法创建CacheManager实例:
说明:
    添加了缓存,当数据有改动的时候,需要清除缓存,如有对数据做增加和修改的时候需要清除相关联的缓存。
    CacheManager 在使用之后应该关闭,虽然有自己的 shutdown hook ,建议在程序中手动关闭。
    CacheManager.getInstance().shutdown();

1、无参

CacheManager manager = new CacheManager();

说明:Ehcache在启动的时候会扫描classes目录下的ehcache.xml配置文件,创建CacheManager对象,如果将ehcache.xml文件放到classes目录下,可以通过无参形式加载配置文件。

2、指定配置文件

CacheManager cm = new CacheManager("E:\\workspaces\\invicme\\src\\main\\resources\\spring\\ehcache.xml");

说明:如果没有将配置文件放在classes目录下,则在ehcache启动的时候找不到配置文件,没有创建CacheManager对象,所以在加载配置文件的时候需要通过路径来加载配置文件;

3、通过资源

URL url = getClass().getResource("/ehcache.xml");
CacheManager manager = new CacheManager(url);

4、通过输入流

InputStream is = InvicmeCacheUtil.class.getClassLoader().getResourceAsStream("spring/ehcache.xml");
// logger.info("url is " + is);
cacheManager = new CacheManager(is);

代码示例

package com.invicme.apps.phshing.util;import java.io.InputStream;
import java.util.Calendar;import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;public class InvicmeCacheUtil {private static final int ONE = 1;private static final String DEFAULT_VALUE = "0001";private static final int LENGTH = 4;// private static final Logger logger = Logger.getLogger(InvicmeCacheUtil .class);static CacheManager cacheManager = null;private static void init () {if (null == cacheManager) {InputStream is = InvicmeCacheUtil.class.getClassLoader().getResourceAsStream("spring/ehcache.xml");// logger.info("url is " + is);cacheManager = new CacheManager(is);}}public synchronized static String generateCode () {init ();Cache cache = null;        if (null == cache) {cache = cacheManager.getCache("invicmeCache");}Calendar calendar = Calendar.getInstance();String year = String.valueOf(calendar.get(Calendar.YEAR));Element element = cache.get(year);if (null == element) {element = new Element(year, ONE);cache.put(element);return year + DEFAULT_VALUE;}int currentValue = Integer.valueOf(String.valueOf(element.getObjectValue()));String str = String.valueOf(currentValue + 1);while (str.length() < LENGTH) {str = "0" + str;}cache.remove(year);    // 清除element = new Element(year, currentValue + 1);cache.put(element);cache.flush();shutdown();return year + str;}private static void shutdown() { if (null != cacheManager) {cacheManager.shutdown(); cacheManager = null;}}
}

单元测试

public class TestInvicmeCacheUtil extends Thread {private static final Logger logger = Logger.getLogger(TestInvicmeCacheUtil.class);public void run () {for (int i = 0; i < 10; i++) {try {Thread.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}logger.info(Thread.currentThread().getName() + ":" + InvicmeCacheUtil.generateCode());}}public static void main(String[] args) {TestInvicmeCacheUtil util0 = new TestInvicmeCacheUtil();util0.setName("util0");TestInvicmeCacheUtil util1 = new TestInvicmeCacheUtil();util1.setName("util1");TestInvicmeCacheUtil util2 = new TestInvicmeCacheUtil();util2.setName("util2");TestInvicmeCacheUtil util3 = new TestInvicmeCacheUtil();util3.setName("util3");util0.start();util1.start();util2.start();util3.start();}
}

转载于:https://blog.51cto.com/luchunli/1726800

Ehcache学习笔记(一)基础入门相关推荐

  1. 1、Latex学习笔记之基础入门篇

    目录 一.Latex基础 1.架构 2.引用.脚注 3.单栏.双栏 4.常用快捷键 5.宏包 6.空格 7.换行.行间距 8.换段 9.下划线 10.引号 11.注释 12.字体 13.缩进 14.超 ...

  2. MySQL数据库 学习笔记 零基础入门 面试 整理

    一.MySQL基础篇 1. 数据库技术的基本概念和方法 1.1 数据库基本概念 1] 数据 数据(Data)指对客观事物进行描述并可以鉴别的符号,这些符号是可识别的.抽象的,不仅仅指狭义上的数字,而是 ...

  3. 《马哥出品高薪linux运维教程》wingkeung学习笔记-linux基础入门课程5

    命令: 内部命令:由shell程序自带的命令叫做内部命令: 外部命令:在系统的某个路径下,有一个与命令同名的可执行程序叫做外部命令. 查看内外部命令的命令:type 命令 命令选项:用于调整命令执行行 ...

  4. 【小迪安全学习笔记】基础入门-Web源码拓展

    前言:Web源码在安全测试中是非常重要的信息来源,可以用来代码审计漏洞也可以用来做信息突破口,其中Web源码有很多技术需要简明分析.比如:获取某ASP源码后可以采用默认数据库下载为突破,获取某其他脚本 ...

  5. Python入门学习笔记1-Python基础

    Python入门学习笔记1-Python基础 前言:本文介绍了Python学习的前导知识概念以及必记基础函数,如善用help方法查看帮助文档,以及内置对象类型的概念以及常用函数的详解. 一.Pytho ...

  6. Uniapp零基础开发学习笔记(5) -组件入门及容器组件使用

    Uniapp零基础开发学习笔记(5) -组件入门及容器组件使用 按照官网教程学习使用组件,并且重点把容器组件的应用进行了练习. 1.官网关于组件的介绍 组件是视图层的基本组成单元,是一个单独且可复用的 ...

  7. Hadoop学习笔记(1) ——菜鸟入门

     Hadoop学习笔记(1) --菜鸟入门 Hadoop是什么?先问一下百度吧: [百度百科]一个分布式系统基础架构,由Apache基金会所开发.用户能够在不了解分布式底层细节的情况下.开发分布式 ...

  8. 【学习笔记】密码学入门(2) 单向散列函数,消息认证码,数字签名,证书

    [学习笔记]密码学入门(2) 单向散列函数,消息认证码,数字签名,证书 学习笔记 2 – 混合密码系统 在密码学入门(1)中提到了基本的密码形式,对称密码和公钥密码以及混合密码系统. 这一部分将学习到 ...

  9. 逐梦旅程学习笔记 DirectX开发入门02:旋转的彩色立方体

    本文是 系列笔记DirectX部分的第2篇,上一篇参见 逐梦旅程学习笔记 DirectX开发入门01:应用程序基本框架 这个示例增加了一些实际的内容,首先是绘制一个颜色随机变幻的彩色立方体,其二是显示 ...

最新文章

  1. 数据库新秀 postgresql vs mongo 性能PK
  2. 提高跑步速度的3个方法
  3. 如何重开固定资产会计年度
  4. C语言再学习 -- 标识符
  5. 想知道大家毕业后的发展道路
  6. Qt学习笔记之事件处理
  7. vue seo关键词设置_SEO关键词优化排名的几个技巧
  8. js 将多个对象合并成一个对象
  9. iOS设计模式——委托(delegate)
  10. 从设计模式到恋爱宝典,程序员们的福利来了
  11. oracle导入10个G的dmp,Oracle11g导出dmp并导入Oracle10g的操作记录
  12. GB/T14710|聊一聊医用电气设备的环境试验
  13. 颜色透明度16进制对照表
  14. QT课程设计:C++英语单词记忆软件程序开发
  15. HTML作业-花店网页
  16. 后台接口被访问到,前台控制台却提示404
  17. php图床_PHP EasyImage 简单图床源码
  18. Compound原理
  19. Centos7 安装Nginx+vsftp
  20. 湖人夺冠,科比MVP!

热门文章

  1. r k-means 分类结果_R语言信用评分卡:数据分箱(binning)
  2. idea学生认证用了一年后过期了怎么办?
  3. 如何删除tmp计算机桌面,Win10系统中tmp文件删除不了应该如何解决?
  4. rmi 反序列化漏洞_提醒:Apache Dubbo存在反序列化漏洞
  5. 如何用catia画半圆_简笔画用半圆画卡通动物
  6. rpython求随机数代码4段5个字符_如何创建一个4位数的随机数并将其存储为变量...
  7. centos离线安装mysql8_CentOS7离线安装Mysql8.0
  8. 加载Hadoop+spark镜像文件需要修改的配置文件
  9. 线程池,这一篇或许就够了
  10. JavaScript中的遍历详解