View Javadoc

1   package net.sf.appstatus.support.spring.cache;
2   
3   import java.util.Collection;
4   import java.util.concurrent.ConcurrentHashMap;
5   import java.util.concurrent.ConcurrentMap;
6   
7   import org.springframework.cache.Cache;
8   import org.springframework.cache.CacheManager;
9   
10  /**
11   * This is an adapter for Spring cache manager which wraps returned cache
12   * instances.
13   * 
14   * <p>
15   * When the cache returns a value and AppStatus is used with useThreadLocal and
16   * a service call is active (IServiceMonitor#beginCall was called), the current
17   * service call is flagged as "cacheHit".
18   * 
19   * <p>
20   * Usage : simply add AppStatusCacheManager as your cacheManager and reference
21   * your previous spring cache manager in your Spring config files.
22   * <p>
23   * With EhCacheManager :
24   * 
25   * <pre>
26   * &lt;bean id="cacheManager" class="net.sf.appstatus.support.spring.cache.AppStatusCacheManager" p:cache-manager-ref="ehCacheCacheManager"/>
27   * 
28   * 
29   * &lt;bean id="ehCacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache"/>
30   * 
31   * &lt;!-- Ehcache library setup -->
32   * &lt;bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="ehcache.xml"/>
33   * </pre>
34   * 
35   * 
36   * @author Nicolas Richeton
37   * 
38   */
39  public class AppStatusCacheManager implements CacheManager {
40  	private CacheManager cacheManager;
41  
42  	private final ConcurrentMap<String, AppStatusCacheAdapter> cacheMap = new ConcurrentHashMap<String, AppStatusCacheAdapter>(
43  			16);
44  
45  	public AppStatusCacheManager() {
46  	}
47  
48  	public Cache getCache(String name) {
49  		Cache cache = cacheManager.getCache(name);
50  		if(cache == null){
51  			return null;
52  		}
53  		AppStatusCacheAdapter result = cacheMap.get(cache.getName());
54  
55  		if (result == null) {
56  			result = new AppStatusCacheAdapter(cache);
57  			cacheMap.put(cache.getName(), result);
58  		}
59  
60  		return result;
61  	}
62  
63  	public Collection<String> getCacheNames() {
64  		return cacheManager.getCacheNames();
65  	}
66  
67  	public void setCacheManager(CacheManager cacheManager) {
68  		this.cacheManager = cacheManager;
69  	}
70  }