您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页ehcache

ehcache

来源:华佗小知识
Ehcache缓存配置

文章分类:Java编程 简介

Cache的配置很灵活,官方提供的Cache配置方式有好几种。你可以通过声明配置、在xml中配置、在程序里配置或者调用构造方法时传入不同的参数。 你可以将Cache的配置从代码中剥离出来,也可以在使用运行时配置,所谓的运行时配置无非也就是在代码中配置。以下是运行时配置的好处:

· 在同一个地方配置所有的Cache,这样很容易管理Cache的内存和磁盘消耗。

· 发布时可更改Cache配置。

· 可再安装阶段就检查出配置错误信息,而避免了运行时错误。 本文将会对ehcache.xml配置文件进行详细的阐述。在配置的时可以拷贝一个现有的ehcache.xml,如果没有请点击这里去下载。 ehcache-failsafe.xml

如果你调用了CacheManager默认构造方法去创建CacheManager的实例,此方法会到classpath中找ehcache.xml文件,否则它会到类路径下找

ehcache-failsafe.xml文件。而ehcache-failsafe.xml被包含在jar包中,所有它肯定能找的到。

ehcache-failsafe.xml提供了一个非常简单的默认配置,这样可以使用户在没有创建ehcache.xml的情况下使用Ehcache。

不过这样做Ehcache会提醒用户创建一个正确的Ehcache配置。

ehcache.xml片段:

maxElementsInMemory=\"10000\" eternal=\"false\"

timeToIdleSeconds=\"120\" timeToLiveSeconds=\"120\" overflowToDisk=\"true\"

maxElementsOnDisk=\"10000000\" diskPersistent=\"false\"

diskExpiryThreadIntervalSeconds=\"120\" memoryStoreEvictionPolicy=\"LRU\" />

ehcache.xml和其他配置文件

在Ehcache-1.6之前的版本,只支持ASCII编码的ehcache.xml配置文件。在

Ehcach-1.6之后版本中,支持UTF8编码的ehcache.xml配置文件。因为向后兼容,所有采用ASCII编码的配置文件完全没有必要转换为UTF8。

一个CacheManager必须要有一个XML配置。由于磁盘路径或是监听端口,多个CacheManager使用同一个配置文件时会出现错误。 下面是ehcache.xml具体实例以及配置指南

DmulticastGroupPort=4446,这样可以配置监听端口。 · DiskStore配置

如果你使用的DiskStore(磁盘缓存),你必须要配置DiskStore配置项。如果不配置,Ehcache将会使用java.io.tmpdir。

diskStroe的“path”属性是用来配置磁盘缓存使用的物理路径的,Ehcache磁盘缓存使用的文件后缀名是.data和.index。 · CacheManagerEventListener配置

我们通过CacheManagerEventListenerFactory可以实例化一个CacheManagerPeerProvider,当我们从CacheManager中added和removed Cache时,将通知CacheManagerPeerProvider,这样一来,我们就可以很方面的对CacheManager中的Cache做一些统计。

注册到CacheManager的事件监听类名有: adding a Cache和removing a Cache · CacheManagerPeerProvider配置

在集群中CacheManager配置CacheManagerPeerProviderFactory创建CacheManagerPeerProvider。具体的实例如下:

RMICacheManagerPeerProviderFactory\"

properties=\"peerDiscovery=manual,

rmiUrls=//server1:40000/sampleCache1|//server2:40000/sampleCache1| //server1:40000/sampleCache2|//server2:40000/sampleCache2\" propertySeparator=\

· CacheManagerPeerListener配置

CacheManagerPeerListener配置是用来监听集群中缓存消息的分发的。 class=\"net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory\"

properties=\"hostName=fully_qualified_hostname_or_ip, port=40001,

socketTimeoutMillis=120000\" propertySeparator=\

·Cache配置

·name:Cache的唯一标识

·maxElementsInMemory:内存中最大缓存对象数。

·maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大。 ·eternal:Element是否永久有效,一但设置了,timeout将不起作用。

·overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中。

·timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。

·timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大。

·diskPersistent:是否缓存虚拟机重启期数据。(这个虚拟机是指什么虚拟机一直没看明白是什么,有高人还希望能指点一二)。

·diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。

·diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。

·memoryStoreEvictionPolicy:当达到maxElementsInMemory时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。这里比较遗憾,Ehcache并没有提供一个用户定制策略的接口,仅仅支持三种指定策略,感觉做的不够理想。

· Cache Exception Handling配置

class=\"com.example.ExampleExceptionHandlerFactory\" properties=\"logLevel=FINE\"/>

总结

这里只对通用缓存的配置做了详细的阐述,至于RMI缓存和集群缓存可以参考这里。

下面给出几个配置示例:

· Ehcache默认Cache配置 maxElementsInMemory=\"10000\" eternal=\"false\"

timeToIdleSeconds=\"120\" timeToLiveSeconds=\"120\" overflowToDisk=\"true\"

diskSpoolBufferSizeMB=\"30\" maxElementsOnDisk=\"10000000\" diskPersistent=\"false\"

diskExpiryThreadIntervalSeconds=\"120\" memoryStoreEvictionPolicy=\"LRU\" />

· SampleCache1配置 简单配置,在ehcache.xml文件中有此配置,在使用Ehcache前最好将其删除掉,自己配置。

缓存名sampleCache1,内存中最多可缓存10000个Element,其中的element会在闲置5分钟或是存活10分钟之后失效。 超过10000element时,element将会输出到磁盘中,输出路径是java.io.tmpdir。 maxElementsInMemory=\"10000\" maxElementsOnDisk=\"1000\" eternal=\"false\"

overflowToDisk=\"true\"

diskSpoolBufferSizeMB=\"20\" timeToIdleSeconds=\"300\" timeToLiveSeconds=\"600\"

memoryStoreEvictionPolicy=\"LFU\" />

· SampleCache2配置

Cache名为SampleCache2,内存中最多可以缓存1000个element,超出1000不能输出到磁盘中。缓存是永久有效的。 maxElementsInMemory=\"1000\" eternal=\"true\"

overflowToDisk=\"false\"

memoryStoreEvictionPolicy=\"FIFO\" />

· SampleCache3配置 Cache名为SampleCache3。可缓存到磁盘。磁盘缓存将会缓存虚拟机重启期的数据。磁盘缓存失效线程运行间隔时间是10分钟。 maxElementsInMemory=\"500\" eternal=\"false\"

overflowToDisk=\"true\" timeToIdleSeconds=\"300\" timeToLiveSeconds=\"600\" diskPersistent=\"true\"

diskExpiryThreadIntervalSeconds=\"1\" memoryStoreEvictionPolicy=\"LFU\" />

· sampleDistributedCache1配置

Cache名为sampleDistributedCache1。 timeToIdleSeconds=\"100\" timeToLiveSeconds=\"100\" overflowToDisk=\"false\"> class=\"net.sf.ehcache.distribution.RMICacheReplicatorFactory\"/>

class=\"net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory\"/>

· sampleDistributedCache2配置

timeToIdleSeconds=\"100\" timeToLiveSeconds=\"100\"

overflowToDisk=\"false\">

class=\"net.sf.ehcache.distribution.RMICacheReplicatorFactory\"

properties=\"replicateAsynchronously=false, replicatePuts=false,

replicateUpdates=true, replicateUpdatesViaCopy=true,

replicateRemovals=false\"/>

· sampleDistributedCache3配置

timeToIdleSeconds=\"100\" timeToLiveSeconds=\"100\" overflowToDisk=\"false\"> class=\"net.sf.ehcache.distribution.RMICacheReplicatorFactory\"

properties=\"asynchronousReplicationIntervalMillis=200\"/>

Ehcache

Recipes and Code Samples

The Recipes and Code Samples page contains recipes - short concise examples for specific use cases - and a set of code samples that will help you get started with Ehcache.

If you have a suggestion or an idea for a recipe or more code samples, please tell us about it using the mailing list or forums.

Recipes

Recipe Web Page and Fragment Caching Data Freshness and Description How to use inluded Servlet Filters to Cache Web Page and Web Page Fragments Expiration Enable Programmatically Caching Empty Values Terracotta How to maintain cache \"freshness\" by configuring TTL and data expiration properly How to enable Terracotta support for Ehcache programmatically Why caching empty values can be desirable to deflect load from the database When many readers simultaneously request the same data element it is called the \"Thundering Herd\" problem. How to prevent it in a single jvm or clustered configuration with Database Overload Caching methods Spring Annotations Cache Wrapper Adding caching to methods using Ehcache Annotations for Spring project A simple class to make accessing Ehcache easier for simple use cases Code Samples

Using the CacheManager

o Singleton versus Instance

o Ways of loading Cache Configuration

o Adding and Removing Caches Programmatically o Shutdown the CacheManager

Creating Caches Programmatically

o Creating a new cache from defaults

o Creating a new cache with custom parameters

Using Caches

o Obtaining a reference to a Cache o Performing CRUD operations o Disk Persistence on demand o Obtaining Cache Sizes

o Obtaining Statistics of Cache Hits and Misses o Dynamically Modifying Cache Configurations o JTA

  

Using Distributed Caches

o Terracotta Example

Cache Statistics and Monitoring

o Registering CacheStatistics in an MBeanServer

More examples

o JCache Examples o Cache Server Examples o Browse the JUnit Tests

Using the CacheManager

All usages of Ehcache start with the creation of a CacheManager.

Singleton versus Instance

As of ehcache-1.2, Ehcache CacheManagers can be created as either singletons (use the create factory method) or instances (use new).

Create a singleton CacheManager using defaults, then list caches.

CacheManager.create();

String[] cacheNames = CacheManager.getInstance().getCacheNames();

Create a CacheManager instance using defaults, then list caches.

CacheManager manager = new CacheManager(); String[] cacheNames = manager.getCacheNames();

Create two CacheManagers, each with a different configuration, and list the caches in each.

CacheManager manager1 = new CacheManager(\"src/config/ehcache1.xml\"); CacheManager manager2 = new CacheManager(\"src/config/ehcache2.xml\"); String[] cacheNamesForManager1 = manager1.getCacheNames(); String[] cacheNamesForManager2 = manager2.getCacheNames();

Ways of loading Cache Configuration

When the CacheManager is created it creates caches found in the configuration.

Create a CacheManager using defaults. Ehcache will look for ehcache.xml in the classpath.

CacheManager manager = new CacheManager();

Create a CacheManager specifying the path of a configuration file.

CacheManager manager = new CacheManager(\"src/config/ehcache.xml\");

Create a CacheManager from a configuration resource in the classpath.

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

Create a CacheManager from a configuration in an InputStream.

InputStream fis = new FileInputStream(new

File(\"src/config/ehcache.xml\").getAbsolutePath()); try {

CacheManager manager = new CacheManager(fis); } finally {

fis.close(); }

Adding and Removing Caches Programmatically

You are not just stuck with the caches that were placed in the configuration. You can create and remove them programmatically.

Add a cache using defaults, then use it. The following example creates a cache called testCache, which will be configured using defaultCache from the configuration.

CacheManager singletonManager = CacheManager.create(); singletonManager.addCache(\"testCache\");

Cache test = singletonManager.getCache(\"testCache\");

Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have been added to a CacheManager.

CacheManager singletonManager = CacheManager.create(); Cache memoryOnlyCache = new Cache(\"testCache\5000, false, false, 5, 2); manager.addCache(memoryOnlyCache);

Cache test = singletonManager.getCache(\"testCache\");

See the cache constructor for the full parameters for a new Cache:

Remove cache called sampleCache1

CacheManager singletonManager = CacheManager.create(); singletonManager.removeCache(\"sampleCache1\");

Shutdown the CacheManager

Ehcache should be shutdown after use. It does have a shutdown hook, but it is best practice to shut it down in your code.

Shutdown the singleton CacheManager

CacheManager.getInstance().shutdown();

Shutdown a CacheManager instance, assuming you have a reference to the CacheManager called manager

manager.shutdown();

See the CacheManagerTest for more examples.

Creating Caches Programmatically

Creating a new cache from defaults

A new cache with a given name can be created from defaults very simply:

manager.addCache(cache name);

Creating a new cache with custom parameters

The configuration for a Cache can be specified programmatically as an argument to the Cache constructor:

public Cache(CacheConfiguration cacheConfiguration) { ... }

Here is an example which creates a cache called test.

//Create a CacheManager using defaults

CacheManager manager = CacheManager.create();

//Create a Cache specifying its configuration.

Cache testCache = new Cache(

new CacheConfiguration(\"test\

.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) .overflowToDisk(true) .eternal(false)

.timeToLiveSeconds(60) .timeToIdleSeconds(30) .diskPersistent(false)

.diskExpiryThreadIntervalSeconds(0)); manager.addCache(cache);

Once the cache is created, add it to the list of caches managed by the CacheManager:

manager.addCache(testCache);

The cache is not usable until it has been added.

Using Caches

All of these examples refer to manager, which is a reference to a CacheManager, which has a cache in it called sampleCache1.

Obtaining a reference to a Cache

Obtain a Cache called \"sampleCache1\

Cache cache = manager.getCache(\"sampleCache1\");

Performing CRUD operations

Put an element into a cache

Cache cache = manager.getCache(\"sampleCache1\"); Element element = new Element(\"key1\cache.put(element);

Update an element in a cache. Even though cache.put() is used, Ehcache knows there is an existing element, and considers the put an update for the purpose of notifying cache listeners.

Cache cache = manager.getCache(\"sampleCache1\"); cache.put(new Element(\"key1\//This updates the entry for \"key1\"

cache.put(new Element(\"key1\

Get a Serializable value from an element in a cache with a key of \"key1\".

Cache cache = manager.getCache(\"sampleCache1\"); Element element = cache.get(\"key1\"); Serializable value = element.getValue();

Get a NonSerializable value from an element in a cache with a key of \"key1\".

Cache cache = manager.getCache(\"sampleCache1\"); Element element = cache.get(\"key1\"); Object value = element.getObjectValue();

Remove an element from a cache with a key of \"key1\".

Cache cache = manager.getCache(\"sampleCache1\"); cache.remove(\"key1\");

Disk Persistence on demand

sampleCache1 has a persistent diskStore. We wish to ensure that the data and index are written immediately.

Cache cache = manager.getCache(\"sampleCache1\");

cache.flush();

Obtaining Cache Sizes

Get the number of elements currently in the Cache.

Cache cache = manager.getCache(\"sampleCache1\"); int elementsInMemory = cache.getSize();

Get the number of elements currently in the MemoryStore.

Cache cache = manager.getCache(\"sampleCache1\");

long elementsInMemory = cache.getMemoryStoreSize();

Get the number of elements currently in the DiskStore.

Cache cache = manager.getCache(\"sampleCache1\"); long elementsInMemory = cache.getDiskStoreSize();

Obtaining Statistics of Cache Hits and Misses

These methods are useful for tuning cache configurations.

Get the number of times requested items were found in the cache. i.e. cache hits

Cache cache = manager.getCache(\"sampleCache1\"); int hits = cache.getHitCount();

Get the number of times requested items were found in the MemoryStore of the cache.

Cache cache = manager.getCache(\"sampleCache1\"); int hits = cache.getMemoryStoreHitCount();

Get the number of times requested items were found in the DiskStore of the cache.

Cache cache = manager.getCache(\"sampleCache1\"); int hits = cache.getDiskStoreCount();

Get the number of times requested items were not found in the cache. i.e. cache misses.

Cache cache = manager.getCache(\"sampleCache1\"); int hits = cache.getMissCountNotFound();

Get the number of times requested items were not found in the cache due to expiry of the elements.

Cache cache = manager.getCache(\"sampleCache1\"); int hits = cache.getMissCountExpired();

These are just the most commonly used methods. See CacheTest for more examples. See Cache for the full API.

Dynamically Modifying Cache Configurations

This example shows how to dynamically modify the cache configuration of an already running cache:

Cache cache = manager.getCache(\"sampleCache\");

CacheConfiguration config = cache.getCacheConfiguration(); config.setTimeToIdleSeconds(60); config.setTimeToLiveSeconds(120); config.setMaxElementsInMemory(10000); config.setMaxElementsOnDisk(1000000);

Dynamic cache configurations can also be frozen to prevent future changes:

Cache cache = manager.getCache(\"sampleCache\"); cache.disableDynamicFeatures();

JTA

A cache will automatically participate in the ongoing UserTransaction when configured in transactionalMode XA. This can be done programmatically:

//Create a CacheManager using defaults

CacheManager manager = CacheManager.create();

//Create a Cache specifying its configuration. Cache xaCache = new Cache(

new CacheConfiguration(\"test\ .overflowToDisk(true) .eternal(false)

.transactionalMode(CacheConfiguration.TransactionalMode.XA)

.terracotta(new

TerracottaConfiguration().clustered(true))); manager.addCache(xaCache);

Or in your CacheManager's configuration file :

maxElementsInMemory=\"500\" eternal=\"false\"

timeToIdleSeconds=\"300\" timeToLiveSeconds=\"600\" overflowToDisk=\"false\" diskPersistent=\"false\"

diskExpiryThreadIntervalSeconds=\"1\" transactionalMode=\"xa\">

Please note that XA Transactional caches are currently only supported when clustered with Terracotta.

The Cache can then be used without any special requirement. Changes will only become visible to others, once the transaction has been committed.

Ehcache cache = cacheManager.getEhcache(\"xaCache\");

transactionManager.begin();

try {

Element e = cache.get(key);

Object result = complexeService.doStuff(element.getValue());

// This put will be rolled back should complexeService.doMoreStuff throw an Exception

cache.put(new Element(key, result));

// Any changes to result in that call, will be visible to others when the Transaction commits

complexeService.doMoreStuff(result);

transactionManager.commit(); } catch (Exception e) {

transactionManager.rollback(); }

Using Distributed Caches

Terracotta Example

See the fully worked examples in the Terracotta Clustering Chapter.

Cache Statistics and Monitoring

Registering CacheStatistics in an MBeanServer

This example shows how to register CacheStatistics in the JDK1.5 platform MBeanServer, which works with the JConsole management agent.

CacheManager manager = new CacheManager(); MBeanServer mBeanServer =

ManagementFactory.getPlatformMBeanServer();

ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);

More examples

JCache Examples

See the examples in the JCache Chapter.

Cache Server Examples

See the examples in the Cache Server Chapter.

Browse the JUnit Tests

Ehcache comes with a comprehensive JUnit test suite, which not only tests the code, but shows you how to use ehcache.

A link to browsable unit test source code for the major Ehcache classes is given per section. The unit tests are also in the src.zip in the Ehcache tarball.

2003-2010 Terracotta, Inc.

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务