ehcache

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具体实例以及配置指南

· CacheManager配置

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.RMICacheManagerPeerListenerFac tory"

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。

maxElementsInMemory="10"

eternal="false"

timeToIdleSeconds="100"

timeToLiveSeconds="100"

overflowToDisk="false">

class="net.sf.ehcache.distribution.RMICacheReplicatorFact ory"/>

class="net.sf.ehcache.distribution.RMIBootstrapCacheLoade rFactory"/>

· sampleDistributedCache2配置

maxElementsInMemory="10"

eternal="false"

timeToIdleSeconds="100"

timeToLiveSeconds="100"

overflowToDisk="false">

class="net.sf.ehcache.distribution.RMICacheReplicatorFact ory"

properties="replicateAsynchronously=false,

replicatePuts=false,

replicateUpdates=true, replicateUpdatesViaCopy=true,

replicateRemovals=false"/>

· sampleDistributedCache3配置

maxElementsInMemory="10"

eternal="false"

timeToIdleSeconds="100"

timeToLiveSeconds="100"

overflowToDisk="false">

class="net.sf.ehcache.distribution.RMICacheReplicatorFact ory"

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

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", maxElements)

.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", which has been preconfigured in the configuration file

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

Performing CRUD operations

Put an element into a cache

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

Element element = new Element("key1", "value1");

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", "value1"));

//This updates the entry for "key1"

cache.put(new Element("key1", "value2"));

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", 1000)

.overflowToDisk(true)

.eternal(false)

.transactionalMode(CacheConfiguration.TransactionalMo de.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);

https://www.360docs.net/doc/fd3400247.html,mit();

} 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.

Ehcache 2 缓存区配置详解

Ehcache 2 缓存区配置详解 第1章Ehcache简介 EhCache是一个开放源码的,基于标准的高速缓存系统。Ehcache可以显著提高应用性能,降低数据库负载,简化应用扩展。Ehcache健壮、功能齐全,也历经了众多应用考验,使得它成为使用最广泛的基于Java的缓存系统。 Ehcache可以支持从进程内的一个或多个节点的部署方式到进程内与进程外混合、高达TB 大小的高速缓存。 Ehcache目前由Terracotta公司维护,使用Apache 2 许可证。 Ehcache截止目前最新版本为2.6。支持多种方式缓存: ●Standalone模式。嵌入应用进程内。单点,多节点间无沟通。 ●Replication模式。嵌入应用内部,通过RMI或JGroup或JMS进行节点同步。 ●Cache Server模式。作为独立缓存服务器,提供REST与WebService接口供访 问。 ●Distributed Caching模式。采用Terracotta Server Array实现高可用的分布式 缓存。 Standalone与Replication均是较传统的使用方式,很多场景下难以满足动态基础设施环境下应用弹性的要求。Cache Server使得缓存服务可以容易的进行水平扩展,但是基于REST与WebService的访问方式降低了缓存访问的效率,不太适合对缓存实时性要求较高的场景。Distributed Caching模式提供了进程内与进程间缓存较理想的结合模式,支持水平扩展,高可用,对网络依赖程度较低,可以很好适应应用弹性伸缩,是动态基础设施条件下较理想的缓存模式。 第2章Ehcache 2 缓存区配置 Ehcache默认配置文件在Ehcache客户端的classpath根目录下,名为ehcache.xml。典型的配置文件如下:

spring配置文件各个属性详解

spring配置文件各个属性详解 分类:spring 2012-08-09 11:25 9316人阅读评论(2) 收藏举报springaophibernateattributesxhtmlwebsphere 目录(?)[+]一、引用外部属性文件 classpath:mail.properties classpath:jdbc.properties 我们定义了一个PropertyPlaceholderConfigurer类的实例,并将其位置属性设置为我们的属性文件。该类被实现为Bean工厂的后处理器,并将使用定义在文件中的属性来代替所有的占位符(${...}value)。 注意: 而在spring2.5的版本中提供了一种更简便的方式,如: 1. 这样以后要使用属性文件中的资源时,可以使用${属性名}来获得。 二、常用数据源的配置 第一种是:DBCP数据源,(需要加入2个jar文件,在spring中的lib下 jakarta-commons/commons-dbcp.jar和commons-pools.jar)主要配置如下:

Spring下Ehcache缓存的配置文档说明

Ehcache缓存单机环境配置 以下的配置是针对DAO层而言的,Controller层不需要做配置。 步骤一:配置pom.xml文件 在文件中引入以下几个依赖项: com.googlecode.ehcache spring-annotations-osgi 1.1.2 commons-codec commons-codec 1.4 net.sourceforge.ehcache https://www.360docs.net/doc/fd3400247.html,.sf.ehcache 2.2.0 步骤二:配置template.mf 在”Import-Package”之后”Excluded-Exports”之前引入三条配置项,注意包名之前要留一个空格,如下红色字体显示部分: Import-Package: org.springframework.context.config;version="[3.0.5,4)", com.googlecode.ehcache.annotations;version="1.1.0", com.googlecode.ehcache.annotations.key;version="1.1.0", org.springframework.aop.aspectj.autoproxy Excluded-Exports: com.mpr.mprsp.mcrc.service.mcrs.publisher.internal.* 步骤三:配置Spring的配置文件applicationContext.xml: 首先在文件的头部加上ehcache的dtd声明,然后配置ehcache缓存管理器。具体配置如下红色字体所示:

ehcache原理

转ehcache 基本原理 hjp222发表于2011-03-22 16:30 最后修改于2011-05-16 15:32 浏览(105) 评论(0)分类:ehcache 举报 ehcache是一个用Java实现的使用简单,高速,实现线程安全的缓存管理类库,ehcache 提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案。同时ehcache作为开放源代码项目,采用限制比较宽松的Apache License V2.0作为授权方式,被广泛地用于Hibernate, Spring,Cocoon等其他开源系统。 Ehcache的类层次模型主要为三层,最上层的是CacheManager,他是操作Ehcache的入口。我们可以通过CacheManager.getInstance()获得一个单个的CacheManager,或者通过CacheManager的构造函数创建一个新的CacheManager。每个CacheManager都管理着多个Cache。而每个Cache都以一种类Hash的方式,关联着多个Elemenat。而Element则是我们用于存放要缓存内容的地方。 ehcache的刷新策略 ehcache的刷新策略是当缓存在放入的时候记录一个放入时间,它是用Lazy Evict的方式,在取的时候同设置的TTL比较 ehcache缓存的3种清空策略: 1 FIFO,先进先出 2 LFU,最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。 3 LRU,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。事件处理 可以为CacheManager添加事件监听,当对CacheManager增删Cache时,事件处理器将会得到通知。要配置事件处理,需要通过ehcache的配置文件来完成。 可以为Cache添加事件监听,当对Cache增删Element时,事件处理器将会得到通知。要配置事件处理,需要通过ehcache的配置文件来完成。 ehcache参数配置: maxInMemory - 设定内存中创建对象的最大值。 eternal - 设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超时限制且元素永不消亡。 timeToIdleSeconds - 设置某个元素消亡前的停顿时间。也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则设置该属性也无用)。 如果该值是0 就意味着元素可以停顿无穷长的时间。 timeToLiveSeconds - 为元素设置消亡前的生存时间。也就是一个元素从构建到消亡的最大时间间隔值。这只能在元素不是永久驻留时有效。 overflowToDisk - 设置当内存中缓存达到maxInMemory 限制时元素是否可写到磁盘上。

SpringBoot下mybatis-一级、二级缓存测试及总结

一、默认开启一级缓存。一级缓存是 SqlSession 级别的。 具体什么意思测试一下。 一次事务中,同一语句调用两次,代码: VarDateEntity varDateEntity = dateMapper.getVarDate(); System.out.println("var1 var:"+varDateEntity.getVarTime()); System.out.println("var1 not:"+varDateEntity.getNotTime()); System.out.println("var1 null:"+varDateEntity.getNullTime()); varDateEntity = dateMapper.getVarDate(); System.out.println("var2 var:"+varDateEntity.getVarTime()); System.out.println("var2 not:"+varDateEntity.getNotTime()); System.out.println("var2 null:"+varDateEntity.getNullTime()); Postman 中执行两次: 测试结果: 结论1: 同一事务中的两次查询,只查询了一次。但是两次事务中,每次均进行了一次查询; 一级缓存的 scope 默认值session; 设置为:statment 。重启 springboot 应用再次测试: 结论2: 设置mybatis.configuration.local-cache-scope=statement后,即使 xmxxxxl 语句中配置useCache="true",一级缓存均失效。 总结: ?Mybatis一级缓存的生命周期和SqlSession一致。 ?Mybatis的缓存是一个粗粒度的缓存,没有更新缓存和缓存过期的概念,同时只是使用了默认的hashmap,也没有做容量上的限定。 ?Mybatis的一级缓存最大范围是SqlSession内部,有多个SqlSession或者分布式的环境下,有操作数据库写的话,会引起脏数据,建议是把一级缓存的默认级别设定为 Statement,即不使用一级缓存。 二、开启二级缓存,需要进行设置。 #一级缓存状态:关闭 # mybatis.configuration.local-cache-scope=statement #二级缓存状态:开启 # mybatis.configuration.cache-enabled=true

大型分布式系统中的缓存架构

大型分布式系统中的缓存架构 本文主要介绍大型分布式系统中缓存的相关理论,常见的缓存组件以及应用场景。 缓存概述 缓存概述 缓存的分类 缓存主要分为四类,如下图:

缓存的分类 CDN 缓存 CDN(Content Delivery Network 内容分发网络)的基本原理是广泛采用各种缓存服务器,将这些缓存服务器分布到用户访问相对集中的地区或网络中。 在用户访问网站时,利用全局负载技术将用户的访问指向距离最近的工作正常的缓存服务器上,由缓存服务器直接响应用户请求。 应用场景:主要缓存静态资源,例如图片,视频。CDN 缓存应用如下图:

未使用 CDN 缓存 使用 CDN 缓存CDN 缓存优点如下图: 优点

反向代理缓存 反向代理位于应用服务器机房,处理所有对 Web 服务器的请求。 如果用户请求的页面在代理服务器上有缓冲的话,代理服务器直接将缓冲内容发送给用户。 如果没有缓冲则先向 Web 服务器发出请求,取回数据,本地缓存后再发送给用户。通过降低向 Web 服务器的请求数,从而降低了 Web 服务器的负载。 应用场景:一般只缓存体积较小静态文件资源,如css、js、图片。 反向代理缓存应用如下图:

反向代理缓存应用图开源实现如下图: 开源实现 本地应用缓存

指的是在应用中的缓存组件,其最大的优点是应用和Cache 是在同一个进程内部,请求缓存非常快速,没有过多的网络开销等。 在单应用不需要集群支持或者集群情况下各节点无需互相通知的场景下使用本地缓存较合适。 同时,它的缺点也是应为缓存跟应用程序耦合,多个应用程序无法直接的共享缓存,各应用或集群的各节点都需要维护自己的单独缓存,对内存是一种浪费。 应用场景:缓存字典等常用数据。 缓存介质如下图所示: 缓存介质 编程直接实现如下图:

mybatis-ehcache-1.0.0-reference

MyBatis EHCache integration-Reference Documentation The MyBatis Community(https://www.360docs.net/doc/fd3400247.html,) Copyright?2010 Copies of this document may be made for your own use and for distribution to others,provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice,whether distributed in print or electronically.

1.The MyBatis EHCache integration (1) 1.1.How to (1)

Chapter1.The MyBatis EHCache integration 1.1.How to EHCache is a widely used java distributed cache for general purpose caching,Java EE and light-weight containers. The EHCache integration is built on top of the ehcache-core and comes without any EHCache3rd part applications.Please refeer to official EHCache documentation if you need plugins. Users that want to use EHCache into their applications,have to download the1.0.0zip bundle,decompress it and add the jars in the classpath;Apache Maven users instead can simply add in the pom.xml the following dependency: then,just configure it in the mapper XML If users need to log cache operations,they can plug the Cache logging version: Users that need to configure EHCache through XML configuration file,have to put in the classpath the /ehcache.xml resource;please refeer to the official EHCache documentation to know more details. If the/ehcache.xml resource is not found or something goes wrong while loading it,the default configuration will be used.

JAVA技术架构及开发规范文档

JAVA技术架构及开发规范文档 1引言 1.1目的 通过对系统整体架构和技术规范的描述.为下一步大规模设计开发提供基础和规范。也希望广大JAVA项目开发的程序猿们提出宝贵的建议.不断完善。 1.2对象与范围 架构师.高级工程师.项目经理.项目管理人员,开发人员.测试人员。 1.3概述 系统实现方案,以实现功能为主.效率性能为辅. 但设计兼顾未来性能的扩展,以减少未来重构的工作量。 wcbapp按逻辑分为两层.第一层用户服务接入. 第二层内部服务。第一层项目不分模块,以二级目录形式表示不同模块,第二层根据不同服务分模块,第 一层和第二层之间使用hessian通信。 第一层和第二层独立部署.第二层的不同模块也可以独立部署。 下项目考虑第一层分模块的二级域名独立部署. 并实现单点登荥。 web app采用集群负载均衡,数据库采用负载均衡和读写分离.以满足一定的性能需求。 文档描述了各层结构和模块使用的技术和框架。最后描述了开发的规范和用到的开发工具。 文档只是描述了项目的架构. 2系统架构图 系统架构如下

3层次和模块 3.1前端负载均衡 Nginx是一个口碑很好的开源免费WEB服务器,国内很多大型网站都转选Nginx平台.比如將讯,豆瓣等。Nginx可以实现动靜分离和web app的负载均衡。 3.1.1动静分离 动靜分离可以很好得分担服务器的负载,有两种方式实现动靜分离。 1. 使用2级域名,配置专门的靜态文件服务器。 2. 利用Nginx的url转发功能,把静态请求转发到靜态服务器或在Nginx本地込理.动态请求转发到应用服务器。 我们目前部署上采用第二种方式.同时也实现第一种方式。系统可以配置动态服务器地址和静态服务器地址,在生成页面时获取这两个地址.对图片、js脚本、css和靜态页面使用静态配置生成url,对ajax清求和动态页面使用动态服务器地址生成urlo 3.1.2负载均衡 Nginx可以配置upstream服务器组,实现组内的负载均衡。通过ip_hash的方式把动态请求转发到组内的某台服务器.同时保证客户端在IP不变的情况下—直访问同一台服务器.解决session保持问题。 3.2 Web app 网站前端,基Tj2ce. spring框架开发。 3.2.1页面展示和控制 系统有三种页面方式。 动态同步请求.通过velocity模板生成页面.客户端刷新整个页面。 ajax异步请求。Ajax舁步请求又有三种形式:与velocity模板结合返回html串:返回json格式;直接返回简单的字符串。 3模板生成的纯静态页面 前台页面采用的框架和第三方技术有:

相关文档
最新文档