Java EE Development Framework (9)-memcached and spring provide cache interface integration

Source: Internet
Author: User

Spring provides the cache interface from 3.x, and the default implementation of spring is the Ehcache,spring caching interface:

Public interface Cache {String getName (); Object Getnativecache (); Valuewrapper get (Object key);<t> T get (Object key, class<t> type); void put (object key, object value); void Evic T (object key), void Clear (), interface Valuewrapper {object get ();}}
From the spring cache interface, we can see that the cache model of spring is to draw a memory area in memory, to specify the name of this disk memory, in this disk memory area in the Key-value way to store data, draw a diagram to illustrate the cache access mode, User and department caches, named Departcache and Usercache, respectively


1. To use spring's cache, first implement CacheManager, you can refer to the implementation of spring to Ehcache, the code to integrate memcached is as follows:

public class Memcachedcachemanager extends Abstracttransactionsupportingcachemanager {private concurrentmap< String, cache> cachemap = new concurrenthashmap<string, cache> ();p rivate map<string, integer> expireMap =   New hashmap<string, integer> ();   The time of the cache private memcachedclient memcachedclient; xmemcached Client Public Memcachedcachemanager () {} @Overrideprotected collection<? Extends Cache> loadcaches () {collection<cache> values = Cachemap.values (); return values;} @Overridepublic Cache GetCache (String name) {Cache cache = Cachemap.get (name), if (Cache = = null) {Integer expire = Expirem Ap.get (name); if (expire = = null) {expire = 0;expiremap.put (name, expire);} cache = new Memcachedcache (name, Expire.intvalue (), memcachedclient); Cachemap.put (name, cache);} return cache;} public void Setmemcachedclient (Memcachedclient memcachedclient) {this.memcachedclient = memcachedclient;} public void Setconfigmap (map<string, integer> configmap) {this.expiremap = confIgMap;}} 
2. Then look at the implementation of the Memcachedcache, the main implementation of the spring cache interface

public class Memcachedcache implements Cache {private final String name;private final MemCache memcache;public MEMCACHEDCA  Che (String name, int expire, memcachedclient memcachedclient) {this.name = Name;this.memcache = new MemCache (name, expire, memcachedclient);} @Overridepublic void Clear () {memcache.clear ();} @Overridepublic void evict (Object key) {Memcache.delete (key.tostring ());} @Overridepublic Valuewrapper get (Object key) {Valuewrapper wrapper = null;object value = Memcache.get (key.tostring ()); (Value! = null) {wrapper = new Simplevaluewrapper (value);} return wrapper;} @Overridepublic String GetName () {return this.name;} @Overridepublic MemCache Getnativecache () {return this.memcache;} @Overridepublic void put (object key, Object value) {Memcache.put (key.tostring (), value);} @Override @suppresswarnings ("unchecked") public <T> T Get (Object key, Class<t> type) {Object Cachevalue = this . Memcache.get (Key.tostring ()); Object value = (Cachevalue! = null? cachevalue:null); if (type! = NULL &&!type.isinstance (value)) {throw new IllegalStateException ("Cached value is not of the required type [" + Ty Pe.getname () + "]:" + value);} Return (T) value;}}
3. The cache API provided by spring is essentially a middle-tier transition between the underlying cache framework and the application, and here is a class called Memcache, which is primarily a model corresponding to the memcached cache, and spring's cache provides only a set of APIs. The specific implementation depends on what caching framework is used for the underlying:

Memcache.java

public class MemCache {private static Logger log = Loggerfactory.getlogger (memcache.class);p rivate set<string> KeySet = new hashset<string> ();p rivate final String name;private final int expire;private final memcachedclient MEMC Achedclient;public MemCache (String name, int expire, memcachedclient memcachedclient) {this.name = Name;this.expire = exp Ire;this.memcachedclient = memcachedclient;} Public Object get (String key) {Object value = null;try {key = This.getkey (key); value = Memcachedclient.get (key);} catch (T  Imeoutexception e) {log.warn ("Get Memcached cache timeout", e),} catch (Interruptedexception e) {log.warn ("Get Memcached cache Interrupted", e);} catch (Memcachedexception e) {log.warn ("Get Memcached cache error", e);} return value;} public void put (String key, Object value) {if (value = = null) return;try {key = This.getkey (key); Memcachedclient.setwithnor Eply (key, expire, value); Keyset.add (key);} catch (Interruptedexception e) {log.warn ("update Memcached cache is interrupted", e);} catch (Memcachedexception e) {Log.warn ("Update Memcached Cache error ", e);}} public void Clear () {for (String Key:keyset) {try {memcachedclient.deletewithnoreply (This.getkey (key))} catch (Interru Ptedexception e) {log.warn ("delete Memcached cache is interrupted", E),} catch (Memcachedexception e) {log.warn ("delete Memcached cache error", e);}} public void Delete (String key) {try {key = This.getkey (key); memcachedclient.deletewithnoreply (key);} catch ( Interruptedexception e) {log.warn ("delete Memcached cache is interrupted", E),} catch (Memcachedexception e) {log.warn ("delete Memcached cache error", E );}} private string GetKey (string key) {return name + "_" + Key;}}
4. Using Memcachedcachemanager in the spring configuration file

<cache:annotation-driven cache-manager= "CacheManager" proxy-target-class= "true"/> <!--turn on cache--><bean Id= "Memcachedclientbuilder" class= "Net.rubyeye.xmemcached.XMemcachedClientBuilder" > <!--configuration memcached cache server- -><constructor-arg><list><bean class= "java.net.InetSocketAddress" ><constructor-arg value = "localhost"/><constructor-arg value= "11211"/></bean></list></constructor-arg></ Bean><bean id= "memcachedclient" factory-bean= "Memcachedclientbuilder" factory-method= "Build" destroy-method= "Shutdown"/><bean id= "CacheManager" class= " Com.hqhop.framework.common.cache.memcached.MemcachedCacheManager "><property name=" memcachedclient "ref=" Memcachedclient "/><!--Configure Cache time--><property name=" Configmap ">            & nbsp <map>                  <entry key= "typelist" value= "3600"/> &nbs P <!--key Cache object nameCall value cache expiration-->            </map>          </proper Ty>  </bean>

5. So far, spring and memcached integration is complete, spring's cache also provides a lot of annotations @Cachable, @cachePut ...



Reference Address:

http://zj0121.iteye.com/blog/1852270

http://jinnianshilongnian.iteye.com/blog/2001040







Java EE Development Framework (9)-memcached and spring provide cache interface integration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.