Full integration of redis and spring

Source: Internet
Author: User

From: http://www.cfanz.cn /? C = article & A = read & id = 32677

Reference http://www.open-open.com/lib/view/open1351324403395.html

Spring http://www.open-open.com/lib/list/354
Data redis implements a subscription/Release System

Spring http://www.blogjava.net/stevenjohn/archive/2012/11/14/391344.html
Redis integration (1)

Download spring-data-redis. Gav is as follows:

<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.0.1.RELEASE</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> <exclusion> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> </exclusion> </exclusions>  </dependency>

Exclusion contains two packages because of conflicts with other packages in the project.

The bean configuration is as follows. You can configure and load the bean file in Web. xml:

<Bean id = "rediscachemanager" class = "com. cr. common. cache. base. rediscachemanger "> <property name =" pool "ref =" shardedjedispool "/> </bean> <! -- Jedis connection pool configuration --> <bean id = "jedispoolconfig" class = "redis. clients. jedis. jedispoolconfig "> <property name =" maxactive "value =" $ {redis. pool. maxactive} "/> <property name =" maxidle "value =" $ {redis. pool. maxidle} "/> <property name =" maxwait "value =" $ {redis. pool. maxwait} "/> <property name =" testonborrow "value =" $ {redis. pool. testonborrow} "/> </bean> <! -- Jedis multiple server configurations --> <bean id = "jedisshardinfo1" class = "redis. clients. jedis. jedisshardinfo "> <constructor-Arg Index =" 0 "value =" $ {redis2.ip} "/> <constructor-Arg Index =" 1 "value =" $ {redis. port} "type =" int "/> </bean> <bean id =" jedisshardinfo2 "class =" redis. clients. jedis. jedisshardinfo "> <constructor-Arg Index =" 0 "value =" $ {redis. IP} "/> <constructor-Arg Index =" 1 "value =" $ {redis. port} "type =" int "/> </be An> <bean id = "shardedjedispool" class = "redis. clients. jedis. shardedjedispool "> <constructor-Arg Index =" 0 "ref =" jedispoolconfig "/> <constructor-Arg Index =" 1 "> <list> <ref bean =" jedisshardinfo1 "/> <ref bean = "jedisshardinfo2"/> </List> </constructor-Arg> </bean> <bean id = "connectionfactory" class = "org. springframework. data. redis. connection. jedis. jedisconnectionfactory "> <property name =" hostname "Val UE = "$ {redis. IP} "/> <property name =" Port "value =" $ {redis. port} "/> <property name =" poolconfig "ref =" jedispoolconfig "/> <! -- <Property name = "shardinfo" ref = "shardedjedispool"> </property> --> </bean> <context: Property-placeholder location = "/WEB-INF/spring/systemcontext. properties "/> <context: component-scan base-package =" org. springframework. data. redis. samples "/>

The property file content is as follows:

Redis. IP = 192.168.1.110 redis2.ip = 192.168.1.112 # port redis. port = 6379 # maximum number of allocated objects redis. pool. maxactive = 1024 # maximum number of objects that can maintain the idel status redis. pool. maxidle = 200 # maximum wait time for redis when no objects are returned in the pool. pool. maxwait = 1000 # Check whether redis is effective when the borrow object method is called. pool. testonborrow = true # Check whether redis is effective when the return object method is called. pool. testonreturn = true


Cache Management Interface:

public interface RedisCache {  public <T> T getRedisCacheInfo(String key);  public <T> boolean setRedisCacheInfo(String key, T value);  }


Cache Management implementation:

public class RedisCacheManger implements RedisCache {  private ShardedJedisPool pool ;  private Logger log = Logger.getLogger(RedisCacheManger.class);  public ShardedJedisPool getPool() { return pool; }  public void setPool(ShardedJedisPool pool) { this.pool = pool; }  public <T> T getRedisCacheInfo(String key) {  try { log.info("get from redisCache :"+key); System.out.println("get from rediscache"); ShardedJedis jedis = pool.getResource(); pool.returnResource(jedis); return (T)jedis.get(key); } catch (Exception e) { e.printStackTrace(); } return null; }   public <T> boolean setRedisCacheInfo(String key, T value) {  try { log.info("add to redisCache :"+key); System.out.println("add to rediscache"); ShardedJedis jedis = pool.getResource(); jedis.set(key, (String)value); pool.returnResource(jedis); return true; } catch (Exception e) { e.printStackTrace(); } return false; } public static void main(String[] args) { new RedisCacheManger().setRedisCacheInfo("12345", "asdfg"); } }


Cache aspect annotation:

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface NeedRedisCached {} 


Cache aspect processing class:

@ Aspect public class rediscacheaspect implements ordered {Private Static logger log = logger. getlogger (rediscacheaspect. class); Private rediscache rediscachemanager; private int ordervalue = 3; Public rediscache getrediscachemanager () {return rediscachemanager;} public void setrediscachemanager (rediscache rediscachemanager) {This. rediscachemanager = rediscachemanager;} @ pointcut ("@ annotation (C Om. JD. bi. ODP. common. cache. core. needrediscached) ") Public void needrediscached () {}@ around (" needrediscached () & ARGs (filter ,..) ") Public object aroundinvoke (proceedingjoinpoint pjp, queryfilter filter) throws throwable {log.info (" Enter aroundinvoke !!! "); If (filter. getvalue () = NULL) {return NULL;} Boolean cacheenabled = commonutil. parseboolean (hbaseconfig. getproperty ("rediscache. enabled "), false); If (cacheenabled) {string md5key = md5util. getmd5 (filter. getvalue (). tostring (); object value = rediscachemanager. getrediscacheinfo (md5key); Boolean flag = false; If (null! = Value) {jsonobject JSON = new jsonobject (value. tostring (); Return JSON;} else if ("null ". equals (value) {return NULL;} else {// execute hbase query value = pjp. proceed (); If (null! = Value) {// determine the non-Cache condition based on the business logic here} else {flag = rediscachemanager. setrediscacheinfo (md5key, value. tostring (); If (FLAG) log.info ("add a cache success by key:" + md5key); else log. warn ("add a cache failure by key:" + md5key) ;}} return value ;}} else {// execute hbase query return pjp. proceed () ;}@ override public int getorder () {return ordervalue;} public int getordervalue () {return ordervalue;} public void setordervalue (INT ordervalue) {This. ordervalue = ordervalue ;}}


If the cache exists, return directly. If the cache does not exist, execute the Data Source Query. hbase queries and set the cache. Section Configuration:

<! -- Redis cache running plane --> <bean id = "rediscacheaspect" class = "com. cr. common. cache. core. rediscacheaspect "> <property name =" ordervalue "value =" 3 "/> <property name =" rediscachemanager "ref =" rediscachemanager "/> </bean> <! -- Configuration declaration --> <AOP: aspectj-autoproxy> <AOP: Include name = "rediscacheaspect"/> </AOP: aspectj-autoproxy>

In this case, if the user's access trigger action on the front-end web page meets the conditions, the slice method will be processed to complete redis cache usage.

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.