怎么创建redis cachemanagerr

> 博客详情
&&&&&&& CacheManager是Ehcache的缓存主要管理类.支持单例模式和工厂模式. 主要用于管理Ehcache里面有的Cache.&&& 可以使用CacheManager来创建Cache.
&&&&&&& 如:&&&&
CacheManager&manager&=&CacheManager.newInstance("src/config/cache.xml");&&&
manager.addCache("testCache");
Cache&cache&=&singletonManager.getCache("testCache");
manager.removeCache("testCache");
& & &&& 具体实现如下:&
&&&&&&& 单例模式:
&&&&&*&The&Singleton&Instance.
&&&&private&static&volatile&CacheManager&
&&&&&*&A&factory&method&to&create&a&singleton&CacheManager&with&default&config,&or&return&it&if&it&exists.
&&&&&*&&p/&
&&&&&*&The&configuration&will&be&read,&{@link&Ehcache}s&created&and&required&stores&initialized.&When&the&{@link&CacheManager}&is&no&longer
&&&&&*&required,&call&shutdown&to&free&resources.
&&&&&*&@return&the&singleton&CacheManager
&&&&&*&@throws&CacheException
&&&&&*&&&&&&&&&&&&&if&the&CacheManager&cannot&be&created
&&&&public&static&CacheManager&create()&throws&CacheException&{
&&&&&&&&if&(singleton&!=&null)&{
&&&&&&&&&&&&LOG.debug("Attempting&to&create&an&existing&singleton.&Existing&singleton&returned.");
&&&&&&&&&&&&return&
&&&&&&&&synchronized&(CacheManager.class)&{
&&&&&&&&&&&&if&(singleton&==&null)&{
&&&&&&&&&&&&&&&&singleton&=&newInstance();
&&&&&&&&&&&&}&else&{
&&&&&&&&&&&&&&&&LOG.debug("Attempting&to&create&an&existing&singleton.&Existing&singleton&returned.");
&&&&&&&&&&&&}
&&&&&&&&&&&&return&
public&static&CacheManager&getInstance()&throws&CacheException&{
&&&&&&&&return&CacheManager.create();
&&& 工厂模式:
CacheManager集合:
private&static&final&Map&String,&CacheManager&&CACHE_MANAGERS_MAP&=&new&HashMap&String,&CacheManager&();
&&&&private&static&final&IdentityHashMap&CacheManager,&String&&CACHE_MANAGERS_REVERSE_MAP&=&new&IdentityHashMap&CacheManager,&String&();
先判断集合中是否存在CacheManger,如里没有,创建一个新的CacheManager并存入集合中.
private&static&CacheManager&newInstance(Configuration&configuration,&String&msg)&throws&CacheException&{
&&&&&&&&synchronized&(CacheManager.class)&{
&&&&&&&&&&&&String&name&=&configuration.getName();
&&&&&&&&&&&&if&(name&==&null)&{
&&&&&&&&&&&&&&&&name&=&DEFAULT_NAME;
&&&&&&&&&&&&}
&&&&&&&&&&&&CacheManager&cacheManager&=&CACHE_MANAGERS_MAP.get(name);
&&&&&&&&&&&&if&(cacheManager&==&null)&{
&&&&&&&&&&&&&&&&LOG.debug(msg);
&&&&&&&&&&&&&&&&cacheManager&=&new&CacheManager(configuration);//此步会存入集合.
&&&&&&&&&&&&}
&&&&&&&&&&&&return&cacheM
初始化Cache,并添加到ehcaches集合中:
&&&&&*&Ehcaches&managed&by&this&manager.
&&&&private&final&ConcurrentMap&String,&Ehcache&&ehcaches&=&new&ConcurrentHashMap&String,&Ehcache&();
private&Ehcache&addCacheNoCheck(final&Ehcache&cache,&final&boolean&strict)&throws&IllegalStateException,&ObjectExistsException,
&&&&&&&&&&&&CacheException&{
&&&&&&&&if&(cache.getStatus()&!=&Status.STATUS_UNINITIALISED)&{
&&&&&&&&&&&&throw&new&CacheException("Trying&to&add&an&already&initialized&cache."&+&"&If&you&are&adding&a&decorated&cache,&"
&&&&&&&&&&&&&&&&&&&&+&"use&CacheManager.addDecoratedCache"&+&"(Ehcache&decoratedCache)&instead.");
&&&&&&&&if&(cache.getCacheConfiguration().isTerracottaClustered()&&&&terracottaClient.getClusteredInstanceFactory()&==&null)&{
&&&&&&&&&&&&throw&new&CacheException(String.format("Trying&to&add&terracotta&cache&%s&but&no&&terracottaConfig&&element&was&"&+
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"used&to&specify&the&Terracotta&configuration&on&the&CacheManager&%s.",
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&cache.getName(),&getName()));
&&&&&&&&Ehcache&ehcache&=&ehcaches.get(cache.getName());
&&&&&&&&if&(ehcache&!=&null)&{
&&&&&&&&&&&&if&(strict)&{
&&&&&&&&&&&&&&&&throw&new&ObjectExistsException("Cache&"&+&cache.getName()&+&"&already&exists");
&&&&&&&&&&&&}&else&{
&&&&&&&&&&&&&&&&return&
&&&&&&&&&&&&}
&&&&&&&&initializingCaches.put(cache.getName(),&cache);
&&&&&&&&try&{
&&&&&&&&&&&&initializeEhcache(cache,&true);
&&&&&&&&&&&&ehcache&=&ehcaches.putIfAbsent(cache.getName(),&cache);
&&&&&&&&&&&&if&(ehcache&!=&null)&{
&&&&&&&&&&&&&&&&throw&new&AssertionError();
&&&&&&&&&&&&}
&&&&&&&&}&finally&{
&&&&&&&&&&&&initializingCaches.remove(cache.getName());
&&&&&&&&//&Don't&notify&initial&config.&The&init&method&of&each&listener&should&take&care&of&this.
&&&&&&&&if&(status.equals(Status.STATUS_ALIVE))&{
&&&&&&&&&&&&cacheManagerEventListenerRegistry.notifyCacheAdded(cache.getName());
&&&&&&&&return&
人打赏支持
码字总数 13680
支付宝支付
微信扫码支付
打赏金额: ¥
已支付成功
打赏金额: ¥缓存框架Ehcache学习(二)多种创建CacheManager的方式 - 推酷
缓存框架Ehcache学习(二)多种创建CacheManager的方式
CacheManager是Ehcache框架的核心类和入口,它负责管理一个或多个Cache对象。要使用Ehcache框架,必须要先创建
CacheManager
对象。现在我们学习下,如何创建
CacheManager
1.使用默认配置文件创建单例对象
CacheManager提供了很多无参的static创建方法,我们可以获取唯一的实例,代码如下:
public static void main(String[] args)
CacheManager mgr1 = CacheManager.getInstance();
CacheManager mgr2 = CacheManager.create();
CacheManager mgr3 = CacheManager.newInstance();
System.out.println(mgr1 == mgr2);// true
System.out.println(mgr1 == mgr3);// true
这3种方式都是等价,获取的唯一实例也是相同的。通过源代码可以很容易的发现,这3个函数就是互相调用的关系。使用这种方式,Ehcahce会报警告,因为我们没有提供自定义的cache配置文件:
警告: No configuration found. Configuring ehcache from ehcache-failsafe.xml& found in the classpath: jar:file:ehcache-2.8.1.jar!/ehcache-failsafe.xml
使用ehcache.jar中默认的缓存配置文件来创建EhcahceManager对象,这种方式实际上使用并不多。默认的配置在大多数情况下,都是不能满足应用程序的使用需要。不推荐这种使用方式。
2.使用自定义的ehcache.xml创建单例对象
使用默认的缓存配置文件,很可能不能满足应用的使用,一般来说应用很少会使用默认的ehcache-failsafe.xml&。这个时候,我们可以自己指定ehcache.xml来创建单一CacheManager对象,使用带有参数的static创建类型的方法。
URL url = TestCacheManager.class.getClassLoader().getResource(&conf/ehcache.xml&);
CacheManager mgr1 = CacheManager.create(url);
CacheManager mgr2 = CacheManager.create(&src/conf/ehcache.xml&);
CacheManager mgr3 = CacheManager.newInstance(&src/conf/ehcache.xml&);
System.out.println(mgr1 == mgr2);// true
System.out.println(mgr1 == mgr3);// true
可以发现:使用CacheManager的static方法,在指定了自定义的缓存配置文件的情况下,创建的仍然是唯一的单例对象。在小规模的应用中,我们可以在ehcache.xml中配置所有需要的&cache&。这样就能够使用一个CacheManager对象,来管理配置文件中的多个&cache&
3.static类型创建方法,有参和无参的区别
CacheManager类static类型的创建方法包括:create()、getInstance()、newInstance(),这些API让我们可以使用默认的缓存配置文件,也可以使用自定义的配置文件,来创建CacheManager对象。一般来说,我们在应用中不会既使用无参的static创建方法,又使用有参的static创建方法。这种使用方式是不合理的,也是没有必要。我有点细节控,还是看下能不能同时使用这2种方式。
CacheManager mgr1 = CacheManager.create(&src/conf/ehcache.xml&);
CacheManager mgr4 = CacheManager.create();
CacheManager mgr5 = CacheManager.getInstance();
CacheManager mgr6 = CacheManager.newInstance();
System.out.println(mgr1 == mgr4);// true
System.out.println(mgr1 == mgr5);// true
System.out.println(mgr1 == mgr6);// false
当使用ehcache.xml创建CacheManager对象的时候,CacheManager中的singleton属性会记录创建的对象值,即创建了CacheManager对象,
singleton会记录该单例对象,不再是null
CacheManager.create()和CacheManager.getInstance()都会先判断
singleton属性是否为null,如果为null则继续调用newInstance(),如果不为null则直接返回。所以mgr1==mgr4==mgr5;
CacheManager.newInstance();不会判断
singleton是否为null,直接使用默认的ehcache-failsafe.xml,新建一个CacheManager对象,所以mgr1 != mgr
通过源码可以发现,它们的调用关系如下:
&4.使用构造函数创建CacheManager对象
CacheManager m1 = new CacheManager();
System.out.println(m1.getName());
CacheManager m2 = new CacheManager(&src/conf/ehcache.xml&);
System.out.println(m2.getName());
System.out.println(m1 == m2);// false
// CacheManager m3 = new CacheManager();
// CacheManager m4 = new CacheManager(&src/conf/ehcache.xml&);
可以看出new出来的对象都是不同实例的,也就是说Ehcache框架支持多个CacheManager对象的情况。特别注意:
同一个缓存配置文件,只能new一个CacheManager对象。如果打开注释代码中的m3 和 m4会报错:
Another CacheManager with same name 'atyManager' already exists in the same VM .Please provide unique names for each CacheManager
具体的情况可以参考我的上一篇博客:
5.个人感悟
1、Ehcache框架的CacheManager的static创建型方法设计存在问题。create()、getInstance()、newInstance()其实都是为了得到CacheManager对象,没有必要提供这么多的API,提供一个简单易用、可读性强的API即可。因为这会让调用者产生困惑,增加学习成本。而且这3个函数存在一些差异,如果使用者不知道,或者不小心调错了函数,会产生错误,这显然不友好的
2、Ehcache以前的版本只支持单例的CacheManager对象,但是在2.8.1版本中,允许通过new的方式,创建多个CacheManager对象。我不知道为什么要提供多个CacheManager对象,也不太明白这样考虑是出于什么目的。不过对我们的应用来说,一个CacheManager对象,管理多个Cache对象,就能满足我们的需要了。
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致使用chcache 缓存
时间: 17:58:29
&&&& 阅读:105
&&&& 评论:
&&&& 收藏:0
标签:在项目里碰到了表单提交和ajax访问后台取到的request对象不是同一个对象,所以不能够资源共享,问了大神决定配置一个缓存来处理这个问题。
引用jar :ehcache-core-2.5.2.jar,ehcache-web-2.0.4.jar
添加 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"&
&!-- 默认缓存 --&
&defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"/&
&!-- 菜单缓存 --&
&cache name="menuCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/&
&/ehcache&
页面引用:存
   // 获取ehcache配置文件中的一个cache
CacheManager cacheManager = CacheManager.create();
Cache sample = cacheManager.getCache("menuCache");
// 获取页面缓存
BlockingCache cache = new BlockingCache(cacheManager.getEhcache("menuCache"));
// 添加数据到缓存中
Element element = new Element("outList", outList);
sample.put(element);
页面引用:取
// 获取ehcache配置文件中的一个cache
CacheManager cacheManager = CacheManager.create();
Cache sample = cacheManager.getCache("menuCache");
// 获取页面缓存
// 添加数据到缓存中
// 获取缓存中的对象,注意添加到cache中对象要序列化 实现Serializable接口
Element result = sample.get("outList");
sample.remove("outList");
List&SystemsetVo& outList
(List&SystemsetVo&) result.getValue();
&&国之画&&&& &&&&chrome插件
版权所有 京ICP备号-2
迷上了代码!spring的cache怎么设置大小,或者超时时间?
来源:csdn
【xml里的配置:
缓存内容:】
miraclestar:
木有人知道吗。。
miraclestar:
好吧,我自己找到了;/2013/07/spring-caching-abstraction-guava-cache.html
楼主能分享一下你的到的结论吗?你留的那个网址不在了
miraclestar:
Spring Caching Abstraction + Guava Cache
Caches are tremendously useful in a wide variety of use cases. For example, you should consider using caches when a value is expensive to compute or retrieve, and you will need its value on a certain input more than once.
A Cache is similar to ConcurrentMap, but not quite the same. The most fundamental difference is that a ConcurrentMap persists all elements that are added to it until they are explicitly removed. A Cache on the other hand is generally configured to evict entries automatically, in order to constrain its memory footprint.
Since version 3.1, Spring Framework provides support for transparently adding caching into an existing
Spring application. Similar to the transaction support, the caching abstraction allows consistent use of
various caching solutions with minimal impact on the code.
To use the cache abstraction, the developer needs to take care of two aspects:
caching declaration - identify the methods that need to be cached and their policy
cache configuration - the backing cache where the data is stored and read from
Note that just like other services in Spring Framework, the caching service is an abstraction (not a cache implementation) and requires the use of an actual storage to store the cache data - that is, the abstraction frees the developer from having to write the caching logic but does not provide the actual stores. There are two integrations available out of the box, for JDK java.util.concurrent.ConcurrentMap and Ehcache.
Declarative caching declaration
Threre are a few annotations in Spring which help us to configure our cache:
@Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method. It's useful to note that default cache key generation occurs depending on method arguments. So,
if method has no arguments, than 0 is used.
if only one param is given, that instance is used as a key.
if more than one afrgument is given, a key computed from hashes of all params is used
More info you can find in javavadoc of DefaultKeyGenerator class. There is an option to provide own implementation of key generator.
@CachePut as opposed to @Cacheable annotation this annotation doesn't cause the method to be skipped - rather it always causes the method to be invoked and its result to be placed into the cache.
@CacheEvict is useful to remove stale data from cache
annotations are not enough to configure our cache. Also we have to enable annotation by specifying &cache:annotation-driven/& in the applicationContext.xml
Method visibility and caching annotations
When using proxies, you should apply caching annotations only to public methods. If you put an annotation on private, protected or package visible method no error is raised, but caching simply will not apply.
Also note that buy default Spring uses JDK proxying mechanism, so implemenation of a service has to be accessed through the service interface. If you access a service directly(without interface) Spring will generate the proxy class(at startup time) but in that case CGLIB 2 should be on classpath(NOTE: Spring 3.2 already has CGLIB2, so if you are the user of that version of Spring, you shouldn't additionally include this library). There is an option to change proxy mode, but be very careful, if you specify proxy-target-class="true on &cache:annotation-driven/&.
Because(from Spring reference):
Multiple &aop:config/& sections are collapsed into a single unified auto-proxy creator at runtime, which applies the strongestproxy settings that any of the &aop:config/& sections (typically from different XML bean definition files) specified. This also applies to the &tx:annotation-driven/& and &aop:aspectj-autoproxy/& elements.
To be clear: using 'proxy-target-class="true"' on &tx:annotation-driven/&, &aop:aspectj-autoproxy/&, &cache:annotation-driven& or &aop:config/&elements will force the use of CGLIB proxies for all three of them.
Configuring Guava Cache as Storage
Out of the box, Spring provides integration with two storages - one on top of the JDK ConcurrentMap and one for ehcache library. To use them, one needs to simply declare an appropriate CacheManager - an entity that controls and manages Caches and can be used to retrieve these for storage.
In project I decided to use Guava's LoadingCache. For that purpose I've created GuavaCacheFactoryBean which helps to configure and create LoadingCache instance. Actually, I used Spring's SimpleCacheManger which uses ConcurrentMap. So, GuavaCacheFactoryBean also converts LoadingCache to ConcurrentMapCache through the Guava's
Cache#asMap() method.
Xml configuration:
&cache:annotation-driven cache-manager="cacheManager"&
&bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"&
&property name="caches"&
&bean parent="parentCacheFactoryBean" p:name="attributes"/&
&bean parent="parentCacheFactoryBean" p:name="history"/&
&bean parent="parentCacheFactoryBean" p:name="actions" p:maxSize="100"/&
&/property&
&bean id="parentCacheFactoryBean" abstract="true" class="com.example.GuavaCacheFactoryBean"
p:expirationAccessTime="120"
p:maxSize="200" /&
NOTE: cache-manager="cacheManager" is a default attribute in &cache:annotation-driven/&
And the GuavaCacheFactoryBean code(getters and setters are omitted):
public class GuavaCacheFactoryBean implements FactoryBean&ConcurrentMapCache& {
private int maxS
private int expirationAccessT
private ConcurrentMap&Object, Object&
private ConcurrentMapC
public ConcurrentMapCache getObject() throws Exception {
public Class&?& getObjectType() {
return ConcurrentMapCache.
public boolean isSingleton() {
@PostConstruct
public void init() {
this.store = CacheBuilder.newBuilder()
.expireAfterAccess(expirationAccessTime, TimeUnit.MINUTES)
.maximumSize(getMaxSize())
.build().asMap();
this.cache = new ConcurrentMapCache(this.getName(), this.store, true);
There are many other options to configure LoadingCache via CacheBuilder, but for the purpose of the project I only need expireAfterAccess and maximumSize.
Here you can see examples of using caching annotations:
@Caching(evict = {
@CacheEvict(value = "attributes", key = CACHE_KEY_EXPR),
@CacheEvict(value = "history", key = CACHE_KEY_EXPR),
@CacheEvict(value = "actions", key = "#p0")
public void saveAction(long arg1, String arg2, long ar3) throws Exception{
//here I make an access to db
In this example I use @Caching annotaion which is simply a grouping annotation for all cache annotations. It is used only if you have to specify a couple caching annotations on method. Also note how I access the method arguments(#p0). It' you can however use argument name, but it may not work since debugging info can not be included in your class files. With key attribute I specify the cache key.
Different storages
To plug another cache back-end you have to provide CacheManager and Cache implementations. That classes tend to be simple adapters that map caching abstraction framework on top of the storage API as the ehcache classes can show.
能说下具体怎么做吗?
免责声明:本站部分内容、图片、文字、视频等来自于互联网,仅供大家学习与交流。相关内容如涉嫌侵犯您的知识产权或其他合法权益,请向本站发送有效通知,我们会及时处理。反馈邮箱&&&&。
学生服务号
在线咨询,奖学金返现,名师点评,等你来互动Shiro/SpringSecurity(8)
SpringMVC(12)
net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each
CacheManager in the config or do one of following:
系统会创建cacheManager
,可是没有beanID,无法用注入方式获取chacheManager,用 ehcache.xml放入src根目录下,可自动创建cache,
如果在任意目录,可在web.xml下添加listener用文件创建cacheManage的方式创建cache
如下配置shiro的缓存时用到了EhCacheCacheManager,因为系统只能创建一个EhCacheCacheManager
所以要让自己的和系统的创建方式来自同一个地方,即使用在classpath路径下通过ehcache.xml配置,
然后让自己和系统的都指向它就可以了,文件名必须是ehcache.xml
&bean id=&ehCacheManager&
class=&org.springframework.cache.ehcache.EhCacheManagerFactoryBean&&
&property name=&configLocation& value=&classpath:/ehcache.xml& /&
&property name=&shared& value=&true& /&
&bean id=&cacheManager& class=&org.springframework.cache.ehcache.EhCacheCacheManager&&
&property name=&cacheManager& ref=&ehCacheManager& /&
&bean id=&shiroCacheManager& class=&org.apache.shiro.cache.ehcache.EhCacheManager&&
&property name=&cacheManager& ref=&ehCacheManager& /&
&&相关文章推荐
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:218035次
积分:3189
积分:3189
排名:第9793名
原创:54篇
转载:302篇
评论:22条
(6)(4)(9)(2)(1)(2)(1)(3)(8)(9)(19)(10)(12)(20)(8)(14)(11)(22)(21)(22)(27)(26)(11)(12)(28)(25)(1)(3)(2)(3)(4)(3)(6)(3)(2)(1)

我要回帖

更多关于 cachemanager 的文章

 

随机推荐