MAVEN uses AOP to increase cache-logical Redis

Source: Internet
Author: User

In the project construction process, the cache logic is necessary to some extent, this article on the basis of the previous MAVEN multi-module project, the use of AOP in the service layer to increase the Redis cache logic.

The specific code has been uploaded git:http://git.oschina.net/alexgaoyh/mutimodule-parent

Specifically, the JUnit unit tests can be performed directly, and the article does not operate on these tests.

Here are some things to note:

<spring-data-redis>1.4.1.release</spring-data-redis><redis.clients.jedis>2.6.0</ Redis.clients.jedis><org.codehaus.jackson>1.9.13</org.codehaus.jackson><dependency> <          Groupid>org.springframework.data</groupid> <artifactId>spring-data-redis</artifactId> <version>${spring-data-redis}</version> </dependency> <dependency> <groupid >redis.clients</groupId> <artifactId>jedis</artifactId> <version>${redis.clie Nts.jedis}</version> </dependency><dependency><groupid>org.codehaus.jackson</groupid ><artifactid>jackson-core-asl</artifactid><version>${org.codehaus.jackson}</version ></dependency><dependency><groupId>org.codehaus.jackson</groupId><artifactId> Jackson-mapper-asl</artifactid><version>${org.codehaus.jackson}</veRsion></dependency> 


<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:           Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans-4.0.xsd "><bean id=" Poolconfig "class=" Redis.clients.jedis.JedisPoolConfig "><property name=" Minidle "value=" 1 "/><property name=" Maxidle " Value= "5"/><property name= "Maxtotal" value= "5"/><property name= "Maxwaitmillis" value= "10001"/>< Property Name= "Testonborrow" value= "false"/></bean><bean id= "jedisconnfactory" class= " Org.springframework.data.redis.connection.jedis.JedisConnectionFactory "><property name=" HostName "value=" 192.168.0.135 "/><property name=" Port "value=" 6379 "/><property name=" password "value=" "/>< Property Name= "Usepool" value= "true"/><property name= "Poolconfig" ref= "Poolconfig"/></bean><!--Redis template definition--><bean id= "redistemplate" class= " Org.springframework.data.redis.core.RedisTemplate "><property name=" ConnectionFactory "ref=" Jedisconnfactory "/><property name=" Keyserializer "><beanclass=" Org.springframework.data.redis.serializer.StringRedisSerializer "/></property><property name=" ValueSerializer "><beanclass=" Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer "/ ></property><property name= "Hashkeyserializer" ><beanclass= " Org.springframework.data.redis.serializer.StringRedisSerializer "/></property><property name=" Hashvalueserializer "><beanclass=" Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer "/></property></bean> </beans>



<!--Redis Cache control layer Begin--><bean id= "Redishandler" class= "Com.alexgaoyh.MutiModule.aop.redis.RedisAdvice" ><property name= "Redistemplate" ref= "Redistemplate" ></property></bean><aop:config> <aop:aspect id= "aspect" ref= "Redishandler" ><!--used between multiple expressions | | , or represents or, uses &&, and represents with,! Represents a non---><!--<aop:pointcut id= "Pointredishandler" expression= "Execution (* com.alexgaoyh.MutiModule.service. *.*.selectbyprimarykey (..)) or Execution (* Com.alexgaoyh.mutimodule.service.*.*.insert (..)) "/>--><aop:pointcut id=" Pointredishandler "expression=" Execution (* com.alexgaoyh.mutimodule.service.*.*. Selectbyprimarykey (..)) "  /><!--<aop:before method= "Dobefore" pointcut-ref= "Pointredishandler"/><aop:after method= "DoAfter" pointcut-ref= "Pointredishandler"/>--><aop:around method= "Doaround" pointcut-ref= "PointRedisHandler"/ ><!--<aop:after-returning method= "Doreturn" pointcut-ref= "Pointredishandler"/&Gt;<aop:after-throwing method= "dothrowing" throwing= "ex" pointcut-ref= "Pointredishandler"/>--&GT;&LT;/AOP: aspect></aop:config><!--Redis Cache control Layer End-->



This trial of AOP is intended to set different AOP facets for different methods, thus avoiding the existence of multiple if else code blocks in the same Doaround method, reducing the existence of code coupling, as of now, for the Select method, the cache logic is added, the next step, You can simply follow this method, synchronous implementation of the update Insert Delete method, the article will not be further described, directly look at the code on the line, JUnit testing is also included.

In the writing process, there is a place to be aware, because when using Redis for a set get operation, the value part is the stored JSON string, then, in the Json->object, you need to get to the converted object type. The specific implementation is as follows:

Package Com.alexgaoyh.mutimodule.aop.redis;import Java.io.serializable;import Org.aspectj.lang.proceedingjoinpoint;import Org.aspectj.lang.reflect.methodsignature;import Org.codehaus.jackson.map.objectmapper;import Org.springframework.dao.dataaccessexception;import Org.springframework.data.redis.connection.redisconnection;import Org.springframework.data.redis.core.rediscallback;import org.springframework.data.redis.core.RedisTemplate; Import Org.springframework.data.redis.serializer.redisserializer;public class Redisadvice {protected RedisTemplate <serializable, serializable> redistemplate;public redistemplate<serializable, Serializable> Getredistemplate () {return redistemplate;} public void Setredistemplate (redistemplate<serializable, serializable> redistemplate) {this.redistemplate = Redistemplate;} /** * Manual control calls the core business logic, as well as pre-and post-call processing, * * Note: When the core business throws an exception, exit immediately, turn to after Advice * Execute after Advice, then go to throwing Advice * object[] ge  Targs: Returns the parameter of the target method Signature getsignature: Returns the signature of the target method* Object Gettarget: Returns the target object that was woven into the enhanced process object Getthis: Returns the proxy object generated by the AOP framework for the target object * @param PJP * @return * @throws throwable */private Object Doaround (Proceedingjoinpoint pjp) throws Throwable {//return value type, the Add method converts the corresponding object to JSON into the cache, and at the time of the Get method, it is returned by the following comment A value type that converts the JSON to the corresponding Object//pjp.gettarget (). GetClass (). Getdeclaredmethod (Pjp.getsignature (). GetName (), (( methodsignature) Pjp.getsignature ()). GetMethod (). Getparametertypes ()). Getreturntype ();//Output Execution ( Demoserviceimpl.insert (..)) Pjp.toshortstring ();//Jump to here the method name is like Insert Selectbyprimarykey//pjp.gettarget (). GetClass (). Getdeclaredmethod ( Pjp.getsignature (). GetName (), ((methodsignature) pjp.getsignature ()). GetMethod (). Getparametertypes ()). GetName (); String Basekey = pjp.toshortstring (); object[] args = Pjp.getargs ();//The If is judged by the Selectbyprimarykey (Integer id) method, i.e.  There is an entry, and the first type of the argument is an integer//late if there is a new method, it is necessary to make the data judgment, can be used for different methods, using different facets if (args! = null && args.length > 0 && Args[0].getclass () = = Integer.class) {System.ouT.println ("key =" + Basekey + "_" + args[0]);                Objectmapper mapper = new Objectmapper ();                Object obj = this.get (Basekey + "_" +args[0]);                if (obj = = null) {//Call core logic Object RetVal = Pjp.proceed ();                This.add (Basekey + "_" +args[0], mapper.writevalueasstring (RetVal));                System.out.println ("Cache is empty");                return retVal;                }else {System.out.println ("cache is not empty");        obj = Mapper.readvalue (obj.tostring (), Pjp.gettarget (). GetClass (). Getdeclaredmethod (Pjp.getsignature (). GetName (),        ((methodsignature) pjp.getsignature ()). GetMethod (). Getparametertypes ()). Getreturntype ());        return obj; }}return null;} /** * Add * @param key * @param value */public void Add (final string key, final string value) {if (redistemplate! = null) {R Edistemplate.execute (New rediscallback<object> () {@Overridepublic Object Doinredis (Redisconnection CoNnection) throws DataAccessException {Connection.set (Redistemplate.getstringserializer (). Serialize (Key),    Redistemplate.getstringserializer (). Serialize (value)); return null;}}); }/** * Gets the object by key */public object Get (final String key) {return Redistemplate.execute (new rediscallback< Object> () {@Overridepublic Object Doinredis (redisconnection connection) throws DataAccessException {byte[] Keybyte = Redistemplate.getstringserializer (). Serialize (key); byte[] value = Connection.get (Keybyte);    String str = Redistemplate.getstringserializer (). Deserialize (value); return str;}    } );          }/** * Get Redisserializer * */protected redisserializer<string> Getredisserializer () {      return Redistemplate.getstringserializer (); }  }



Execution effects such as

The key selection is to use

Pjp.toshortstring () + "_"  + args[0]

So you can avoid key conflicts.

And note the following piece of code: Json->object, it is necessary to know the current data type, get the service layer request method return method.

Return value type, the Add method converts the corresponding object to JSON into the cache, and at the time of the Get method, converts the JSON to the corresponding Object//pjp.gettarget () by the return value type of the following comment. GetClass (). Getdeclaredmethod (Pjp.getsignature (). GetName (), ((methodsignature) pjp.getsignature ()). GetMethod (). Getparametertypes ()). Getreturntype ();






MAVEN uses AOP to increase cache-logical Redis

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.