Use spring Interceptor to customize cache implementation instance code, spring instance
This article focuses on the implementation of custom cache using spring Interceptor. The specific implementation code is as follows.
Memcached is a high-performance distributed memory object Cache System for dynamic Web applications to reduce database load. It caches data and objects in the memory to reduce the number of reads to the database, thus improving the speed of dynamic and database-driven websites. This article uses the Memcached instance and spring Interceptor to implement custom cache implementation. The Interceptor is used to read custom cache labels and generate key values.
Custom Cacheable
package com.jeex.sci;@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Cacheable {String namespace();String key() default "";int[] keyArgs() default {};String[] keyProperties() default {};String keyGenerator() default "";int expires() default 1800;}Custom CacheEvict
package com.jeex.sci;@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface CacheEvict {String namespace();String key() default "";int[] keyArgs() default {};String[] keyProperties() default {};String keyGenerator() default "";}Spring usually implements MethodInterceptor public Object invoke (MethodInvocation invocation) throws Throwable
public Object invoke(MethodInvocation invoction) throws Throwable {Method method = invoction.getMethod();Cacheable c = method.getAnnotation(Cacheable.class);if (c != null) {return handleCacheable(invoction, method, c);}CacheEvict ce = method.getAnnotation(CacheEvict.class);if (ce != null) {return handleCacheEvict(invoction, ce);}return invoction.proceed();}Process cacheable labels
private Object handleCacheable(MethodInvocation invoction, Method method, Cacheable c) throws Throwable {String key = getKey(invoction, KeyInfo.fromCacheable(c));if (key.equals("")) {if (log.isDebugEnabled()){log.warn("Empty cache key, the method is " + method);}return invoction.proceed();}long nsTag = (long) memcachedGet(c.namespace());if (nsTag == null) {nsTag = long.valueOf(System.currentTimeMillis());memcachedSet(c.namespace(), 24*3600, long.valueOf(nsTag));}key = makeMemcachedKey(c.namespace(), nsTag, key);Object 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 = " + key);}o = invoction.proceed();memcachedSet(key, c.expires(), o);}return o;}Process cacheEvit labels
private Object handleCacheEvict(MethodInvocation invoction, CacheEvict ce) throws Throwable { 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("Evicting " + key); } memcachedDelete(key); } } return invoction.proceed(); } Generate key based on parameters
// Generate the private String getKeyWithArgs (Object [] args, int [] argIndex) {StringBuilder key = new StringBuilder (); boolean first = true; for (int index: argIndex) {if (index <0 | index> = args. length) {throw new IllegalArgumentException ("Index out of bound");} if (! First) {key. append (':');} else {first = false;} key = key. append (args [index]);} return key. toString ();}Generate key based on Attribute
Private String getKeyWithProperties (Object o, String props []) throws Exception {StringBuilder key = new StringBuilder (); boolean first = true; for (String prop: props) {// convert the bean property to the String methodName = "get" + prop. substring (0, 1 ). toUpperCase () + prop. substring (1); Method m = o. getClass (). getMethod (methodName); Object r = m. invoke (o, (Object []) null); if (! First) {key. append (':');} else {first = false;} key = key. append (r);} return key. toString ();}Generate a key using a custom Generator
// Generate key private String getKeyWithGenerator (MethodInvocation invoction, String keyGenerator) throws Exception {Class <?> Ckg = Class. forName (keyGenerator); CacheKeyGenerator ikg = (CacheKeyGenerator) ckg. newInstance (); return ikg. generate (invoction. getArguments ());}Help class for saving key information
private static class 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.keyGenerator = ce.keyGenerator();ki.keyProperties = ce.keyProperties();return ki;}String key() {return key;}int[] keyArgs() {return keyArgs;}String[] keyProperties() {return keyProperties;}String keyGenerator() {return keyGenerator;}}Parameter settings
// Use the parameter to set key @ Cacheable (namespace = "BlackList", keyArgs = {0, 1}) public int anotherMethond (int a, int B) {return 100 ;}Test class:
package com.jeex.sci.test;import net.spy.memcached.MemcachedClient;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;public class TestMain {public static void main(String args[]) throws InterruptedException{ApplicationContext ctx = new FileSystemXmlApplicationContext("/src/test/resources/beans.xml");MemcachedClient mc = (MemcachedClient) ctx.getBean("memcachedClient");BlackListDaoImpl dao = (BlackListDaoImpl)ctx.getBean("blackListDaoImpl");while (true) {System.out.println("################################GETTING START######################");mc.flush();BlackListQuery query = new BlackListQuery(1, "222.231.23.13");dao.searchBlackListCount(query);dao.searchBlackListCount2(query);BlackListQuery query2 = 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.searchBlackListCount3(query2);Thread.sleep(300);}}}Summary
The above is all about implementing instance code using spring interceptor custom cache. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!