A principal pesquisa deste artigo é usar o interceptador da Spring à implementação de cache personalizada, e o código de implementação específico é o seguinte.
O Memcached é um sistema de cache de objetos de memória distribuído de alto desempenho para aplicativos dinâmicos da Web para reduzir a carga do banco de dados. Reduz o número de vezes que o banco de dados é lido por dados e objetos em cache na memória, aumentando assim a velocidade dos sites dinâmicos e orientados por banco de dados. Este artigo usa a instância e o interceptador de mola para implementar a personalização do cache. Use o interceptador para ler tags de cache personalizadas e estratégia de geração de valor -chave.
pacote com.jeex.sci; @target (elementType.method) @retention (retentionPolicy.Runtime) @InHerited @Documented public @Interface cache {string namesace (); string key () padrão ""; int [" expires () padrão 1800;} pacote com.jeex.sci; @target (elementType.method) @retention (retentionPolicy.Runtime) @InHerited @Documented public @Interface cacheeVict {string namesace (); string key () padrão ""; int [] keyargs () default {}; "";} Public Object Invoke (MethodInvocation Invoction) lança lotável {Método Method = Invoction.getMethod (); cache c = métod.getannotation (cacheable.class); if (c! = null) {return handleCachAche (invocção, método, c); cacheArtErvict ce = método.getAntation; handlecacheevict (invocção, ce);} return injeção.proeced ();} Manutenção de objetos privados (MethodInvocation Invocção, método do método, cache c) lança arremesso {string key = getKey (invocção, keyInfo.fromcacheable (c); NSTAG = (LONG) MEMCACHEDGET (c.NamesPace ()); if (NSTAG == NULL) {NSTAG = Long.ValueOf (System.CurrentTimemillis ()); MemcachedSet (C.Namespace (), 24*3600, Long.Valueof (NSTAGS); = null; o = memcachedget (key); if (o! = null) {if (log.isdebugenabled ()) {log.debug ("cache hit: cache key =" key);}} else {if (log.isdebugenabled ()) {log.debug "cache (if (log.isdebugen ()) {log.debug" Invoction.proeced (); MemcachedSet (Key, c.expires (), o);} retornar o;} Private Object HandleCacheeVict (MethodInvocation Invoction, Cacheevict CE) lança arremesso {String key = getKey (invocção, keyinfo.fromcacheevict (CE)); if (key.equals ("")) {if (log.isdebugenabled ()) {log.debug ("evitando" + ce.namespace ()); } memcachedDelete (ce.namespace ()); } else {long nsTag = (long) memcachedget (ce.namespace ()); if (nsTag! = null) {key = makememcachedKey (ce.namespace (), nsTag, chave); if (log.isdebugenabled ()) {log.debug ("evitando" + key); } memcachedDelete (chave); }} retornar injeção.proeced (); } // Use parâmetros interceptados ao método para gerar parâmetros privados string getKeywithargs (object [] args, int [] argindex) {stringbuilder key = new stringBuilder (); booleano primeiro = true; for (int Índice: argindex) {if (index <0 || index> = args.length) {lança novo ilegalargumentException ("índice fora do limite"); } if (! primeiro) {key.append (':'); } else {primeiro = false; } key = key.append (args [index]); } return key.toString (); } private string getKeywithProperties (objeto o, string props []) lança exceção {stringbuilder key = new StringBuilder (); booleano primeiro = true; para (String prop: props) {// converte a propriedade do feijão no nome do método string métodname = "get" + prop.substring (0, 1) .touppercase () + prop.substring (1); Método m = o.getclass (). GetMethod (métodname); Objeto r = m.invoke (o, (objeto []) nulo); if (! primeiro) {key.append (':'); } else {primeiro = false; } key = key.append (r); } return key.toString (); } // Use o gerador para gerar a tecla String privada GetKeyWithGenerator (injeção de MethodInvocation, String KeyGenerator) lança a exceção {classe <?> Ckg = class.ForName (KeyGenerator); CacheKeyGenerator ikg = (cacheKeyGenerator) ckg.newInstance (); return ikg.generate (invoction.getarguments ()); } classe estática privada keyInfo {string key; int [] keyargs; string keyproperties []; string keyGenerator; estático keyinfo do cache (cache c) {keyinfo ki = new KeyInfo (); ki.key = c.Key (); ki.ekeyargs = c.args (); c.KeyGenerator (); ki.KeyProperties = c.KeyProperties (); retorna ki;} keyInfo estático deCacheeVict (Cacheevict CE) {Keyinfo ki = new Keyinfo (); ki.key = ce.key (); ki.keyargs = ce.args (); Ce.KeyGenerator (); Ki.KeyProperties = Ce.KeyProperties (); Return ki;} String key () {return key;} int [] keyargs () {return Keyargs;} string [] keyProperties () {return KeyProperties;} String; // Defina a tecla com parâmetros @cacheable (namespace = "Blacklist", keyargs = {0, 1}) public int outro metond (int a, int b) {return 100; } pacote com.jeex.sci.test; importar net.spy.memcached.memcachedClient; importar org.junit.test; importar org.springframework.context.applicationContext; import org.springframework.support.filication args []) lança interruptedException {ApplicationContext ctx = new FileSystemxMLApplicationContext ("/src/test/Resources/beans.xml"); memcachedclient mc = (memcachedclient) ctx.getbean ("memcachedClient"); negra; (Blacklistdaoimpl) ctx.getbean ("Blacklistdaoimpl"); while (true) {System.out.println("############################################################################## NONás########## .############ .######ásh################ .############ .####áshon############## .#####áshon##########áshon#########áshonáshonás..-########h. NONás########## .############ .######ásh################ .############ .####áshon############## .#####áshon##########áshon#########áshonáshonás..-########h. NONás######### .############### .############ .####ásh############# .########### .########### .######áshonáshonáshon########áshon#######áshon######HONG. Inicie ###################################t "); mc.flush (); BlackListQuery Query = new BlackListQuery (1," 222.231.23.13 "); DAO.SearchBlackListcount (Queryyyyyyyery231.23.13"); New BlackListQuery (1, "123.231.23.14"); dao.anothermethond (333, 444); dao.searchBlackListCount2 (Query2); dao.searchBlackListCount3 (query2); dao.evict (consulsão); dao.searchBlackListCount2 (query2); dao.evictall (); dao.earchBlackListCount2 (Query2);O exposto acima é o conteúdo inteiro deste artigo sobre o código de exemplo de implementação para cache personalizado usando o interceptador da Spring, e espero que seja útil para todos. Amigos interessados podem continuar se referindo a outros tópicos relacionados neste site. Se houver alguma falha, deixe uma mensagem para apontá -la. Obrigado amigos pelo seu apoio para este site!