Annotation-based SPRINGAOP Redis caching technology

Source: Internet
Author: User
Tags aop

This blog post mainly describes how to implement cache development using SPRINGAOP + Redis + annotations. First, term description 1, Springaop AOP (Aspect oriented programming), the technology of aspect-oriented programming. AOP is a useful complement to OOP based on the IOC Foundation. The SPRINGAOP can be configured so that the code has almost no coupling intrusion. The
2, Redis Redis is an open-source, Web-enabled log-and-Key-value database that uses the ANSI C language and provides multiple language APIs. Redis has become a model of NoSQL. 3, annotations in the form of annotations, so that the code is not intrusive, dynamic configurable. second, thinking when the data has not changed, using local data, if the data has changed, then get the latest data from the database and cache to the local (can be cached in various ways, such as HTML5 can be used localstorge), reference to the following figure three, major code snippets 1, Pom.xml, for integrating spring and Redis

<!--Redis Cache database ... start-->
<dependency>
	<groupid>org.springframework.data</ groupid>
	<artifactId>spring-data-redis</artifactId>
	<version>1.6.1.release</ version>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.7.3</version>
</dependency >
<!--redis cache Related.....end-->

2, Spring-dispather
<aop:aspectj-autoproxy proxy-target-class= "true"/>
3, Springcontent, configure Redis connection
<!--Redis and cache configuration start--> <!--Jedis configuration--> <bean id= "Poolconfig" class= "> <property name=" maxidle "value=" ${redis.maxidle} "/> <property name=" Maxwaitmillis "value=" ${r edis.maxwait} "/> <property name=" Testonborrow "value=" ${redis.testonborrow} "/> </bean > <!--RE Dis Server Center--> <bean id= "ConnectionFactory" class= " Org.springframework.data.redis.connection.jedis.JedisConnectionFactory "> <property name=" poolconfig "ref=" Poolconfig "/> <property name=" port "value=" ${redis.port} "/> <property name=" hostName "value=" ${r Edis.host} "/> <!--<property name=" password "value=" ${redis.password} "/>--> <property Nam E= "Timeout" value= "${redis.timeout}" ></property> </bean > <bean id= "redistemplate" Org.springframework.data.redis.core.RedisTemplate "> <property name=" connectionfactory "ref=" connEctionfactory "/> <property name=" Keyserializer "> <bean class=" Org.springframework.data.redis . Serializer. Stringredisserializer "/> </property> <property name=" ValueSerializer "> <bean CLA ss= "Org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> </bean > <!- -Cache configuration--> <bean id= "Putcache" class= "Com.ninesky.framework.PutCacheAOP" > <property name= "Redistempl" Ate "ref=" redistemplate "/> </bean> <!--cache configuration--> <bean id=" GetCache "class=" .  GETCACHEAOP "> <property name=" redistemplate "ref=" Redistemplate "/> </bean> <!--redis and cache configuration end -->
4, Redis.properties
#redis中心
#绑定的主机地址
redis.host=127.0.0.1
#指定Redis监听端口, the default port is 6379
redis.port=6379 
# Authorization password (not used in this example)
redis.password=
#最大空闲数: When the number of idle links is greater than Maxidle, the recycle
redis.maxidle=100  
#最大连接数: can be established simultaneously " Maximum number of links "
redis.maxactive=300  
#最大等待时间: Unit ms
redis.maxwait=1000   
#使用连接时, detecting connection Success 
Redis.testonborrow=true 
#当客户端闲置多长时间后关闭连接, if specified as 0, to turn off the feature
5. Custom Annotations(1) Generate cached version Putcache.java
/**
 * Custom annotations, update the corresponding version when inserting, updating, or deleting
 * @author chenth * *
 *
@Retention (retentionpolicy.runtime)
@Target ({elementtype.method}) public
@interface Putcache {
	String name () default "";
	String value () default "";
}
(2) Get cached version Getcache.java
/**
 * Custom annotations, add the annotation to the query using caching method
 * @author chenth *
 *
@Retention (retentionpolicy.runtime)
@Target ( {Elementtype.method})
Public @interface GetCache {
	String name () default "";
	String value () default "";
}
6. Join AOP(1), getcache corresponding slice
@Aspect public class Getcacheaop {private redistemplate<serializable, object> redistemplate;
	Threadlocal<long> time=new threadlocal<long> ();
	
	Threadlocal<string> tag=new threadlocal<string> ();
		@Pointcut ("@annotation (Com.ninesky.classtao.springaop.annotation.GetCache)") public void GetCache () {
	System.out.println ("I am an entry point"); /** * @getcache in all marked places * @param joinpoint/@Before ("GetCache ()") public void Beforeexec (Joinpoint Joinpo
		int) {methodsignature ms= (methodsignature) joinpoint.getsignature ();
		Method Method=ms.getmethod ();
		String actionname = method.getannotation (getcache.class). Name ();
		String FieldList = method.getannotation (Getcache.class). Value (); For (String field:fieldList.split (",")) {if ("school_id". Equals (field)) actionname+= "#" +actionutil.getschoolid (
			);
			else if ("user_id". Equals (field)) actionname+= "#" +actionutil.getuserid (); else if ("User_type". Equals (field)) actionname+= "#" +actionUtil.getusertype ();
		else actionname+= "#" +actionutil.getparameter (field);
		} valueoperations<serializable, object> operations =redistemplate.opsforvalue ();
		Actionutil.setcache (TRUE);
			If this is the first time the value is taken. The version is stored in the Redis database if (Operations.get (actionname) ==null) {operations.increment (actionname, 1);
		Return } if (Operations.get (ActionName). Equals (Actionutil.getparameter ("cache_version")) throw new Cacheexception ("Data not updated
		, you can use local data! ");
	Actionutil.setcache_version (Operations.get (actionname) + ""); } public void Setredistemplate (redistemplate<serializable, object> redistemplate) {this.redistemplate = re
	Distemplate; }
}
(2), putcache corresponding slice
@Aspect public class Putcacheaop {private redistemplate<serializable, object> redistemplate;
	Threadlocal<long> time=new threadlocal<long> ();
	
	Threadlocal<string> tag=new threadlocal<string> ();
		@Pointcut ("@annotation (Com.ninesky.classtao.springaop.annotation.PutCache)") public void Putcache () {
	System.out.println ("I am an entry point"); /** * @putcache in all marked places * @param joinpoint/@After ("Putcache ()") public void Afterexec (Joinpoint joinpoin
		T) {methodsignature ms= (methodsignature) joinpoint.getsignature ();
		Method Method=ms.getmethod ();
		String actionname = method.getannotation (putcache.class). Name ();
		String FieldList = method.getannotation (Putcache.class). Value ();
		For (String field:fieldList.split (",")) actionname+= "#" +actionutil.getparameter (field);
		Valueoperations<serializable, object> operations =redistemplate.opsforvalue ();
	Operations.increment (ActionName, 1); } public void Setredistemplate (redistemplate&Lt
	Serializable, object> redistemplate) {this.redistemplate = redistemplate; }
}
7, finally, add the annotation in the controller
/**
 * Add message (Campus style, Party building)
 * @param
 request
/@PutCache (name= "Newslist", value= "School_id,news_code")
@RequestMapping (value= "/addnews") public
@ResponseBody Object addnews (httpservletrequest request) {
	Newsvo vo = Beanutil.formattobean (newsvo.class);
	Newsservice.addnews (VO);
	Newsservice.addinformation (VO);
	Return responseutils.sendsuccess (VO);

/**
 * Get the message list (WEB)
 * @param request
 *
 @return
/@GetCache (name= "Newslist", value= "School_ Id,news_code ")
@RequestMapping (value="/getnewslistforweb ") public
@ResponseBody Object getnewslist ( HttpServletRequest request) {
	Newsvo vo = Beanutil.formattobean (newsvo.class);
	if (Integerutil.isempty (vo.getschool_id ()))
		vo.setschool_id (Actionutil.getschoolid ());
	list<newsvo> list = Newsservice.getnewslist (VO);
	return responseutils.sendsuccess (list);
8, successful, this method reduces the application of the database request times and time consumption, improve the query efficiency


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.