La principale recherche de cet article est d'utiliser l'intercepteur de Spring en implémentation de cache personnalisée, et le code d'implémentation spécifique est le suivant.
Memcached est un système de mise en cache d'objet de mémoire distribué haute performance pour les applications Web dynamiques afin de réduire la charge de base de données. Il réduit le nombre de fois où la base de données est lue par des données et des objets en cache en mémoire, augmentant ainsi la vitesse des sites Web dynamiques axés sur la base de données. Cet article utilise l'instance Memcached et Spring Interceptor pour implémenter la personnalisation du cache. Utilisez l'intercepteur pour lire les balises de cache personnalisées et la stratégie de génération de valeur clé.
package com.jeex.sci; @target (elementType.Method) @retention (retenderPolicy.runtime) @Inherited @Documented public @Interface Cacheable {String namespace (); string key () Default ""; int [] keyargs () default {}; string [] keyproperties () Default {}; string keyGenerrad () "in introperties () Default {}; string keyGenerrad ()" int. expire () par défaut 1800;} package com.jeex.sci; @target (elementType.Method) @retention (retenderPolicy.runtime) @inherited @Documented public @interface cacheevict {String namespace (); string key () default ""; int [] keyargs () defautel {}; string [] keyproperties () defautel {}; string keyGener invoque d'objet public (méthodinvocation invoction) lance le lancement {méthode méthode = invoction.getMethod (); cacheable c = method.getAnnotation (cacheable.class); if (c! = null) {return handlecacheable (invoction, méthode, c);} cacheevict ce = méthode.getannotation (cacheevict.class); if (ce! = null) handlecacheevict (invoction, ce);} retour injection.proceed ();} objet privé Handlecacheable (MethodInvocation Invoction, méthode Méthode, Cacheable C) lance Throwsable {String key = getKey (Invoction, keyInfo.FromCacheable (c)); if (key.equal nstag = (long) memcachedGet (c.Namespace ()); if (nstag == null) {nstag = long.valueof (system.currenttimemillis ()); memcachedset (c.Namespace (), 24 * 3600, long.valueof (nstag));} key = makemMcachedKey Key); objet 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 =" + clés); invoction.proceed (); memcachedset (key, c.expires (), o);} return o;} objet privé handlecacheevict (méthodinvocation invoction, cacheevict ce) lève le throwable {string key = getKey (invocction, keyinfo.fromcacheevict (ce)); if (key.equals ("")) {if (log.isdebugeNabled ()) {log.debug ("eviting" + ce.Namespace ()); } memCachedDelete (ce.Namespace ()); } else {long nstag = (long) memcachedGet (ce.Namespace ()); if (nstag! = null) {key = makeMeMcachedKey (ce.Namespace (), nStag, key); if (log.isdebugeNable ()) {log.debug ("eviting" + key); } memcachedDelete (key); }} return injection.proceed (); } // Utiliser les paramètres interceptés à la méthode pour générer des paramètres de chaîne privée getKeyWithArgs (objet [] args, int [] argindex) {stringBuilder key = new StringBuilder (); booléen d'abord = true; pour (int index: argindex) {if (index <0 || index> = args.length) {throw new illégalArgumentException ("index Out of Bound"); } if (! d'abord) {key.append (':'); } else {premier = false; } key = key.append (args [index]); } return key.toString (); } String privé getKeyWithProperties (objet O, String props []) lève l'exception {stringBuilder key = new StringBuilder (); booléen d'abord = true; for (String Prop: Props) {// Convertit la propriété du bean au nom de la méthode String Methodnname = "Get" + Prop.SubString (0, 1) .toupperCase () + Prop.SubString (1); Méthode m = o.getClass (). GetMethod (méthodyName); Objet r = M.Invoke (o, (objet []) null); if (! d'abord) {key.append (':'); } else {premier = false; } key = key.append (r); } return key.toString (); } // Utilisez le générateur pour générer une chaîne privée clé getKeyWithGenerator (méthodinvocation injection, string keyGenerator) lève exception {class <?> Ckg = class.forname (keyGenerator); CacheKeyGenerator ikg = (cacheKeyGenerator) ckg.newinstance (); return ikg.generate (invoction.getArguments ()); } classe statique privée keyInfo {string key; int [] keyargs; string keyproperties []; string keyGenerator; static keyInfo FromCacheable (cacheable c) {keyInfo ki = new KeyInfo (); ki.key = c.key (); ki.keyargs = c.keyargs (); ki.KeyGenerator = 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.keygorator = ce.KeyGenerator (); ki.keyproperties = ce.keyproperties (); return ki;} string key () {return key;} int [] keyargs () {return keyargs;} string [] keyproperties () {return keyproperties;} string keyGenerator () {return keyGenerator;}} // Définit la clé avec paramètres @Cacheable (namespace = "BlackList", keyargs = {0, 1}) public int autretMethond (int a, int b) {return 100; } package com.jeex.sci.test; import net.spy.memcached.memcachedClient; import org.junit.test; import org.springframework.context.applicationContext; import org.springframework.context.support.fileSystemxmlapplicationContex InterruptedException {applicationContext ctx = new FileSystemXmlApplicationContext ("/ Src / Test / Resources / Beans.xml"); MemcachedClient MC = (MemcachedClient) CTX.getBean ("MemcachedClient"); BlackListDaoimpl Dao = (BlackListDaoil) CTX.GetBan ("BlackListDaOIMPL"); (vrai) {System.out.println("############################################################################## ##############################################################################################################################. ##############################################################################################################################. #####################################################################################################################################################. Démarrer ##################################### ”); mc.flush (); BlackListQuery Query = New BlackListQuery (1," 222.231.23.13 "); Dao.SearchBlackLack BlackListQuery (1, "123.231.23.14"); dao.anothermethond (333, 444); dao.searchBlackListCount2 (query2); dao.searchblacklistCount3 (query2); dao.evict (query); dao.searchblackListCount2 (query2); evictall (300);}}}}Ce qui précède est l'intégralité du contenu de cet article sur l'exemple d'implémentation Code pour le cache personnalisé à l'aide de l'intercepteur de Spring, et j'espère que cela sera utile à tout le monde. Les amis intéressés peuvent continuer à se référer à d'autres sujets connexes sur ce site. S'il y a des lacunes, veuillez laisser un message pour le signaler. Merci vos amis pour votre soutien pour ce site!