您好ehcache的世界范例? [英] hello world example for ehcache?

查看:62
本文介绍了您好ehcache的世界范例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ehcache是​​一个可高度配置的野兽,示例非常复杂,通常涉及许多层接口。

ehcache is a hugely configurable beast, and the examples are fairly complex, often involving many layers of interfaces.

有没有人遇到过最简单的示例,它只是缓存某些内容就像是内存中的单个数字(未分配,没有XML,尽可能少的java行)。然后将该数字缓存60秒,然后下一个读取请求使该数字获得新值(例如,通过调用Random.nextInt()或类似方法)

Has anyone come across the simplest example which just caches something like a single number in memory (not distributed, no XML, just as few lines of java as possible). The number is then cached for say 60 seconds, then the next read request causes it to get a new value (e.g. by calling Random.nextInt() or similar)

请不要用Spring。

No Spring please.

推荐答案

EhCache带有故障安全配置,该配置具有一些合理的到期时间(120秒)。这足以启动并运行它。

EhCache comes with a failsafe configuration that has some reasonable expiration time (120 seconds). This is sufficient to get it up and running.

导入:

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

然后,创建缓存非常简单:

Then, creating a cache is pretty simple:

CacheManager.getInstance().addCache("test");

这将创建一个名为 test 的缓存。您可以有许多不同的,独立的缓存,这些缓存均由相同的 CacheManager 管理。将(键,值)对添加到此缓存很简单:

This creates a cache called test. You can have many different, separate caches all managed by the same CacheManager. Adding (key, value) pairs to this cache is as simple as:

CacheManager.getInstance().getCache("test").put(new Element(key, value));

检索给定键的值很简单:

Retrieving a value for a given key is as simple as:

Element elt = CacheManager.getInstance().getCache("test").get(key);
return (elt == null ? null : elt.getObjectValue());

如果您在默认的120秒有效期后尝试访问元素,则缓存将返回null(因此检查 elt 是否为空)。您可以通过创建自己的 ehcache.xml 文件来调整有效期-该文件在ehcache网站上不错。

If you attempt to access an element after the default 120 second expiration period, the cache will return null (hence the check to see if elt is null). You can adjust the expiration period by creating your own ehcache.xml file - the documentation for that is decent on the ehcache site.

这篇关于您好ehcache的世界范例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆