Redis non-intrusive caching of business query data

Source: Internet
Author: User
Tags data structures hash redis

This is based on our own business characteristics (very few are updated and do not require accurate data, some queries are longer), we use Redis as a cache, using Hash data structures to cache data.

Our business queries are the integration of multiple DAO through the service layer to complete the DTO assembly, based on the business characteristics, there is no need to cache individual DAO data, but instead directly cache the service's final DTO results.

First, instantiate the redistemplate in Spring Boot:

@Configuration public class Redisconfig {private static final Logger Logger = Logger.getlogger (Redisconfig.class); @Bean public redisconnectionfactory genfactory () {jedisconnectionfactory jedisconnectionfactory = new JedisConnectionF
		Actory ();
		Jedisconnectionfactory.sethostname ("192.168.1.82");
		Jedisconnectionfactory.setusepool (TRUE);
	return jedisconnectionfactory; } @Bean public redistemplate<string, object> redistemplate (Redisconnectionfactory Factory) {logger.info ("Enter Re The Disconfig.redistemplate () method .....
		");
		redistemplate<string, object> redistemplate = new redistemplate<> ();
		Redistemplate.setkeyserializer (New Stringredisserializer ());
		Redistemplate.sethashkeyserializer (New Stringredisserializer ());
		Redistemplate.sethashvalueserializer (New jackson2jsonredisserializer<> (Object.class));
		Redistemplate.setvalueserializer (New jackson2jsonredisserializer<> (Object.class));
		Redistemplate.setconnectionfactory (Factory); RetUrn Redistemplate; }
}

Of course, the Pom.xml file has to be supplemented with Redis dependencies:

<dependency>  
	<groupId>org.springframework.boot</groupId>  
	<artifactId> Spring-boot-starter-data-redis</artifactid>
Then, define an annotation that adds this annotation to the service.get** method that expects the data to be cached:
@Documented//Document  
@Retention (retentionpolicy.runtime)//Can get @Target at run time  
(Elementtype.method)//action to class, method, Interface Top Public
@interface Curiecache {
}
For example, we want to cache the following query results, directly add annotations:
@CurieCache public
cohortdefinitiondto Getcohortprocesssummarybyid (Integer defid) {					
	list<conceptdata > datas = new arraylist<conceptdata> ();
	...
}
Finally, let the cache work, see Around Advice, detailed explanation already in this class of comments:

Import Java.lang.reflect.Method;
Import Org.aspectj.lang.ProceedingJoinPoint;
Import Org.aspectj.lang.annotation.Around;
Import Org.aspectj.lang.annotation.Aspect;
Import Org.aspectj.lang.reflect.MethodSignature;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.data.redis.core.RedisTemplate;

Import org.springframework.stereotype.Component; /** * 1. Query results for service layer using Redis Hash cache * 2. Key uses the class name + method name, * 3. The value of either field is concatenated with the string string of the parameter, and the default value of * 4 is used if no argument is available. 
The get** method that expects the result to be cached needs only to add a custom Curiecache annotation, which is intercepted: * A. If the cache has the data directly from the cache * B. Otherwise the business query is executed before the final result is placed in the cache before returning * @author Allen */
	
	@Component @Aspect public class Redisadvice {private Logger Logger = Loggerfactory.getlogger (Redisadvice.class);
	
	@Autowired private redistemplate<string, object> redistemplate;  
    @Around ("Execution (* com.hebta.curie.service.*service.get* (..))") Public Object Aroundmethod (Proceedingjoinpoint PJP) Throws Throwable {methodsignature methodsignature = (methodsignature) pjp.getsignature ();		
		Method method = Methodsignature.getmethod ();
		String key = null;
		String field = null;
			if (Method.isannotationpresent (Curiecache.class)) {Logger.info ("current method set Curiecache annotations");
			String target = Pjp.gettarget (). toString ();
			StringBuilder kSb = new StringBuilder (); Ksb.append (Target.substring (Target.lastindexof (".") + 1, Target.indexof ("@")). Append (":"). Append (Method.getname (
			));
			
			Key = Ksb.tostring ();
			
			Logger.info ("target is: {}, Key is: {}", Target, key);
				if (Pjp.getargs (). length > 0) {logger.info ("method {} No Parameters", Method.getname ());
				StringBuilder sb = new StringBuilder ();
				For (Object Obj:pjp.getArgs ()) {Sb.append (obj.tostring ());
			} field = Sb.tostring ();
			} else {field = "blank";
			
			} logger.info ("field is: {}", field);
			if (Redistemplate.opsforhash (). Haskey (Key, field)) {Logger.info ("The result in the cache is taken directly from the cache");	Return Redistemplate.opsforhash (). Get (Key, field);
				} else {Logger.info ("The result is not cached, calculated first, cached, and then returned");
				Object result = Pjp.proceed ();
				Redistemplate.opsforhash (). Put (Key, field, result);
			return result;
			}} else {Logger.info ("no curiecache annotations");
		return Pjp.proceed (); }		
	}
}




Related Article

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.