La investigación principal en este documento es utilizar la implementación del interceptor de caché de Spring, y el código de implementación específico es el siguiente.
MEMCACHED es un sistema de almacenamiento en caché de objetos de memoria distribuidos de alto rendimiento para aplicaciones web dinámicas para reducir la carga de la base de datos. Reduce el número de veces que la base de datos se lee mediante datos y objetos en caché en la memoria, aumentando así la velocidad de los sitios web dinámicos basados en la base de datos. Este artículo utiliza la instancia de Memcached y el interceptor de Spring para implementar la personalización de caché. Use el interceptor para leer etiquetas de caché personalizadas y estrategia de generación de valor clave.
paquete com.JEEX.sci; @Target (elementType.method) @Retention (retentionPolicy.runtime) @inherited @Documented public @interface Cacheable {String NamesPace (); String Key () default ""; int [] keyargs () predeterminado {}; string [] keyproperties () predeterminado {}; string keyGenerator () ")") predeterminado 1800;} paquete com.JEEX.sci; @Target (elementType.method) @Retention (retentionPolicy.runtime) @inhered @Documented public @interface CacheeVict {String NamesPace (); String Key () Default ""; int [] keyargs () predeterminado {}; string [] Keyproperties () predeterminado {} Public Object Invoke (MethodInVocation Invoction) lanza lando {método método = invoction.getMethod (); cacheo c = método.getAnnotation (cachable.class); if (c! = null) {return handLecAceable (invoction, método, c);} CacheeVict ce = Method.getAntation (CacheeVict.Class); if (CE! HandLecacheEvict (Invoction, CE);} return inyection.proced ();} Private Object HandLecachable (MethodInVocation Invoction, Method Method, Cacheable C) lanza shrewable {string key = getKey (invoction, keyInfo.FromCachable (c)); if (key.equals ("")) {if (log.isdeBugeNabled ()) {log.warn ("vacío clave de cache, el método es" + método);} returnytection (} de regreso (} nstag = (long) memcachedget (c.namespace ()); if (nstag == null) {nstag = long.ValueOf (system.currentTimemillis ()); memcachedset (c.namespace (), 24*3600, long.ValueOf (nstag));} clave = MAKEMEMCACHECHEKEKEKKEKKEKKEKKEKKEKEKKEKEKEKKEAKEKEKECKECE (),),),),). key); objeto o = null; o = memcachedget (key); if (o! = null) {if (log.isDebugeNabled ()) {log.debug ("cache hit: cache key =" + key);}} else {if (log.isdebugenabled ()) {log.debug ("cache miss: cache key =" invoction.proced (); memcachedset (clave, c.expires (), o);} return o;} Objeto privado HandLecacheEvict (MethodInVocation Invoction, CacheEvict CE) lanza lanzable {string key = getKey (invoction, keyInfo.fromCacheEvict (ce)); if (key.equals ("")) {if (log.isDebugeNabled ()) {log.debug ("Evicting" + Ce.namespace ()); } memcachedDelete (ce.namespace ()); } else {long nstag = (long) memcachedget (ce.namespace ()); if (nstag! = null) {key = makememCachedKey (ce.namespace (), nstag, key); if (log.isDebugeNabled ()) {log.debug ("Evictar" + Key); } memcachedDelete (clave); }} return inyection.proced (); } // Use parámetros interceptados al método para generar parámetros String privado getKeywithargs (objeto [] args, int [] argindex) {stringBuilder key = new StringBuilder (); booleano primero = verdadero; for (int index: argIndex) {if (index <0 || index> = args.length) {tire nueva ilegalArgumentException ("índice fuera de límite"); } if (! Primero) {Key.append (':'); } else {primero = false; } key = key.append (args [index]); } return key.ToString (); } String private getKeywithProperties (objeto o, string props []) lanza la excepción {stringBuilder key = new StringBuilder (); booleano primero = verdadero; for (string pro: props) {// Convierta la propiedad de Bean al nombre del método String MethodName = "Get" + Prop.Substring (0, 1) .ToUpperperCase () + prop.substring (1); Método m = o.getClass (). GetMethod (MethodName); Objeto r = m.invoke (o, (objeto []) nulo); if (! Primero) {key.append (':'); } else {primero = false; } key = key.append (r); } return key.ToString (); } // Use el generador para generar una cadena privada clave getKeyWithGenerator (inyección MethodInVocation, String KeyGenerator) lanza la excepción {class <?> ckg = class.forname (keyGenerator); CacheKeyGenerator IKG = (CacheKeyGenerator) ckg.newinstance (); return ikg.generate (invoction.getArGuments ()); } clase static privada keyInfo {string key; int [] keyargs; string keyProperties []; string keyGenerator; static keyInfo fromCacheable (cacheo C) {keyInfo ki = new KeyInfo (); ki.key = c.key (); ki.keyargs = C.Keyargs (); ki.keygerator = = = = = = = C.KeyGenerator (); ki.keyproperties = C.KeyProperties (); return ki;} static keyInfo fromCacheEvict (CacheEvict CE) {KeyInfo ki = new KeyInfo (); Ki.Key = CE.Key (); ki.keyargs = ce.keyargs (); ki.keyGenerator = ce.KeyGenerator (); ki.keyproperties = ce.keyproperties (); return ki;} string key () {return key;} int [] keyargs () {return keyargs;} string [] keyProperties () {returnProperties;} string keyGenerator () {return keyGenerator;}}}} // Establecer la tecla con parámetros @Cacheable (Namespace = "BlackList", Keyargs = {0, 1}) public int otro Methond (int a, int b) {return 100; } paquete com.JEEX.sci.test; import net.spy.memcached.memCachedClient; import org.junit.test; import org.springframework.context.ApplicationContext; importar org.springframework.context.support.FilsystemXmlaPplicationContextExt; args []) lanza interruptedException {applicationContext ctx = new FilesMystemMLAplaPlicationContext ("/src/test/recursos/beans.xml"); memcachedclient mc = (memcachedClient) ctx.getBean ("memcachedclient"); blacklistDaoMeMPl dao = = (BlackListDaoImpl) CTX.getBean ("BlackListDaoImpl"); While (verdadero) {System.out.println("############################################################################## ##########################################################################################################################################. ##########################################################################################################################################. ######################################################################################################################################. Inicio ################################# "); MC.FLUSH (); BlackListQuery Query = new BlackListQuery (1," 222.231.23.13 "); Dao.SearchBlackListCount (Query); DaO.SearchblistCount2 (Qualery); QUEYY); BUSTERY; BUSTERY; BUSTERY) New BlackListQuery (1, "123.231.23.14"); Dao.Anothermethond (333, 444); Dao.SearchblackListCount2 (Query2); Dao.SearchBlackListCount3 (Query2); Dao.evict (Query); Dao.SearchBlackListCount2 (Query); Dao.Evictall (); Dao.SearchBlackList3 (Query2); Query.sleep (300);}}}Lo anterior es todo el contenido de este artículo sobre el código de ejemplo de implementación para caché personalizado utilizando el interceptor de Spring, y espero que sea útil para todos. Los amigos interesados pueden continuar referiéndose a otros temas relacionados en este sitio. Si hay alguna deficiencia, deje un mensaje para señalarlo. ¡Gracias amigos por su apoyo para este sitio!