Redis Spring Cache Configuration

Source: Internet
Author: User
Tags delete key

The idea of using Redis as a cache is to configure the interceptor in the spring project, make slices on the service layer, and intercept on methods such as FINDXXX or getxxx to determine if caching is possible.

1. Environment: Spring 3.1.2 + Spring data redis 1.0.0+ Jedis 2.1.0

2.spring configuration file configuration:

 <!--Jedis configuration--<bean id= "Poolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <propert          Y name= "Maxidle" value= "${redis.maxidle}"/> <property name= "maxactive" value= "${redis.maxactive}"/> <property name= "maxwait" value= "${redis.maxwait}"/> <property name= "Testonborrow" value= "${redis . Testonborrow} "/> </bean > <bean id=" connectionfactory "class=" org.springframework.data.redis.c Onnection.jedis.JedisConnectionFactory "> <property name=" poolconfig "ref=" Poolconfig "/> <p          Roperty name= "Port" value= "${redis.port}"/> <property name= "hostName" value= "${redis.host}"/> <property name= "Password" value= "${redis.password}"/> <property name= "Timeout" value= "${redis.timeout} "></property> </bean > <bean id=" redistemplate "class=" Org.springframework.data.redis.core.RedisT Emplate "> &Lt;property name= "ConnectionFactory" ref= "ConnectionFactory"/> <property name= "KeySerializer" > <bean class= "Org.springframework.data.redis.serializer.StringRedisSerializer"/> &lt ;/property> <property name= "ValueSerializer" > <bean class= "ORG.SPRINGF Ramework.data.redis.serializer.JdkSerializationRedisSerializer "/> </property> </bean > < !--Cache Configuration--<bean id= "Methodcacheinterceptor" class= "Com.xxx.cache.MethodCacheInterceptor" > < Property Name= "Redisutil" ref= "Redisutil"/> </bean > <bean id= "redisutil" class= "Com.xxx.framework.util . Redisutil "> <property name=" redistemplate "ref=" redistemplate "/> </bean > <bean id=" met Hodcachepointcut "class=" Org.springframework.aop.support.RegexpMethodPointcutAdvisor "> <property n      Ame= "Advice" >        <ref local= "Methodcacheinterceptor"/> </property> <property name= "Patterns" > <list> <!--requires a cached method regular expression---<value> com\.xxx\. *\.service\. Impl\. *list.*</value > <value> com\.xxx\. *\.service\. Impl\. *find.*</value > <value> com\.xxx\. *\.service\. Impl\. *get.*</value > </list> </property> </bean >

3.redis Tool Class

Import Java.io.serializable;import Java.util.set;import Java.util.concurrent.timeunit;import Org.apache.log4j.logger;import Org.springframework.data.redis.core.redistemplate;import org.springframework.data.redis.core.valueoperations;/** * Redis Cache Tool Class * */public final class Redisutil {private Logge R logger = Logger.getlogger (redisutil.class);p rivate redistemplate<serializable, object> redisTemplate;/*** Bulk delete the corresponding value* * @param keys*/public void Remove (final String ... keys) {for (string Key:keys) {remove (key);}} /*** Bulk Delete key* * @param pattern*/public void Removepattern (final String pattern) {set<serializable> keys = Redistempl Ate.keys (pattern); if (keys.size () > 0) redistemplate.delete (keys); /*** Delete the corresponding value* * @param key*/public void Remove (final String key) {if (Exists (key)) {Redistemplate.delete (key);}} /*** determines if there is a corresponding value* * @param key* @return */public Boolean exists (final String key) {return Redistemplate.haskey (key) in the cache;} /*** Read Cache * * @param key* @return */public objecT get (final String key) {Object result = null; Valueoperations<serializable, object> operations = Redistemplate.opsforvalue (); result = Operations.get (key); return result;} /*** Write Cache * * @param key* @param value* @return */public Boolean set (Final String key, Object value) {Boolean result = False ; try {valueoperations<serializable, object> operations = Redistemplate.opsforvalue (); Operations.set (key, value ); result = true;} catch (Exception e) {e.printstacktrace ();} return result;} /*** Write Cache * * @param key* @param value* @return */public Boolean set (Final String key, Object Value,long expiretime) {Boolea n result = false;try {valueoperations<serializable, object> operations = Redistemplate.opsforvalue (); O Perations.set (key, value); Redistemplate.expire (key,expiretime,timeunit.seconds); result = true;} catch (Exception e) {e.printstacktrace ();} return result;} public void Setredistemplate (redistemplate<serializable, object> redistemplate) {this.redistemplate = Redistemplate;}}

4. Global Cache Blocker

Import Java.io.inputstream;import java.util.arraylist;import Java.util.list;import Java.util.properties;import Org.aopalliance.intercept.methodinterceptor;import Org.aopalliance.intercept.methodinvocation;import Org.apache.log4j.logger;import Com.xxx.framework.util.redisutil;import Framework.utils.string.stringutil;public Class Methodcacheinterceptor implements Methodinterceptor {private Logger Logger = Logger.getlogger (methodcacheinterce Ptor.    Class);    Private Redisutil Redisutil; Private list<string> targetnameslist; Service name not added to the cache private list<string> methodnameslist; Method name not added to cache private Long defaultcacheexpiretime; Cache default Expiration time private long xxxrecordmanagertime; Private Long Xxxsetrecordmanagertime;  /** * Initialization reads the class name and method name that do not need to be added to the cache */public methodcacheinterceptor () {try {InputStream in             = GetClass (). getClassLoader (). getResourceAsStream ("cacheconf.properties");    Properties P = new properties ();         P.load (in);             Split string string[] Targetnames = P.getproperty ("Targetnames"). Split (",");                           string[] Methodnames = P.getproperty ("Methodnames"). Split (",");              Load Expiration Time Setting Defaultcacheexpiretime = long.valueof (P.getproperty ("Defaultcacheexpiretime"));              Xxxrecordmanagertime = long.valueof (P.getproperty ("Com.service.impl.xxxRecordManager"));              Xxxsetrecordmanagertime = long.valueof (P.getproperty ("Com.service.impl.xxxSetRecordManager"));              Create List targetnameslist = new arraylist<string> (targetnames.length);             Methodnameslist = new arraylist<string> (methodnames.length); Integer maxlen = targetnames. Length > Methodnames.length?              TargetNames.length:methodNames.length;  Add the class name and method name that do not need to be cached to list for (int i = 0; i < MaxLen; i++) {if (I < targetnames.length) {TarGetnameslist.add (Targetnames[i]);                 } if (I < methodnames.length) {Methodnameslist.add (methodnames[i]);         }}} catch (Exception e) {e.printstacktrace (); }} @Override public Object invoke (Methodinvocation invocation) throws Throwable {Object value = nul         L         String targetName = Invocation.getthis (). GetClass (). GetName ();          String methodName = Invocation.getmethod (). GetName ();              Content that does not need to be cached if (!isaddcache (Stringutil.substrforlastdot (targetName), methodName)) {//Execution method returns results         return Invocation.proceed ();         } object[] arguments = invocation.getarguments ();         String key = Getcachekey (TargetName, methodName, arguments); System.          OUT.PRINTLN (key);             try {//To determine if there is a cache if (Redisutil. Exists (key)) {return redisutil. Get (key);}//write Cache value = Invocation.proceed ();                  if (value = null) {final String TKey = key;                  Final Object TValue = value;                           New Thread (New Runnable () {@Override public void run () { if (Tkey.startswith ("Com.service.impl.xxxRecordManager")) {Redisutil.set (TKey, TValue                          , xxxrecordmanagertime); } else if (Tkey.startswith ("Com.service.impl.xxxSetRecordManager")) {Redisutil.set (TKey, TV                          Alue,xxxsetrecordmanagertime);                          } else{Redisutil.set (TKey, tvalue,defaultcacheexpiretime);             }}). Start ();              }} catch (Exception e) {e.printstacktrace (); if (value = = null) {return INVOCATION.PROCEEd ();    }} return value;          }/** * Whether to join the cache * @return */Private Boolean Isaddcache (String targetName, String methodName) {          Boolean flag = true;         if (targetnameslist. Contains (targetName) | | methodnameslist.contains (methodName)) {flag = false;    } return flag; }/** * Create Cache Key * * @param targetName * @param methodName * @param arguments */private Stri Ng Getcachekey (String targetName, String methodName, object[] arguments) {StringBuffer SBU = new Stri        Ngbuffer ();          Sbu.append (TargetName). Append ("_"). Append (MethodName);                  if (arguments! = null) && (arguments.length! = 0)) {for (int i = 0; i < arguments.length; i++) {             Sbu.append ("_"). Append (Arguments[i]);    }} return sbu.tostring (); } public void Setredisutil (Redisutil redisutil) {this.redisutil = Redisutil; }}

The above code is doped with some of the business logic is not too good, can continue to optimize the ha.

5.redis.properties file

redis.host=127.0.0.1redis.port=6379redis.password=redis.maxidle=100redis.maxactive=300redis.maxwait= 1000redis.testonborrow=trueredis.timeout=100000

6.cacheconf.properties file

# do not need to add cached classes and methods # not add cache service Nametargetnames=xxxrecordmanager,xxxsetrecordmanager, xxxstatisticsidentificationmanager# not add Cache method namemethodnames= #设置过期时间com. service.impl.xxxrecordmanager= 60com.service.impl.xxxsetrecordmanager= 60defaultcacheexpiretime=3600

7. Note that splicing key requires the corresponding class to generate the ToString method, otherwise the serialization failure error may occur.

Redis Spring Cache Configuration

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.