Spring Redis Integration

Source: Internet
Author: User
Tags delete key redis xmlns redis server
1. First introduce code base
<!--Redis Cache  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 End--
2. Introduction of Spring Redis configuration information: Redisconfig.xml

and then introduce it in spring.

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd "> <!--Jedis configuration-<bean id=" Poolconfig
        "class=" Redis.clients.jedis.JedisPoolConfig "> <property name=" maxidle "value=" ${redis.maxidle} "/> <property name= "Maxwaitmillis" value= "${redis.maxwait}"/> <property name= "Testonborrow" value= "${red Is.testonborrow} "/> </bean> <!--redis Server Center--<bean id=" redisconnectionfactory "class=" O Rg.springframework.data.redis.connection.jedis.JedisConnectionFactory "> <property name=" poolconfig "ref=" Poolconfig "/> <property name=" port "value=" ${redis.port} "/> <property name=" hostName "value=" ${redis . host} "/> <property name= "Password" value= "${redis.password}"/> <property name= "Timeout" value= "${redis.timeout}" ></property&
    Gt </bean> <bean id= "redistemplate" class= "Org.springframework.data.redis.core.RedisTemplate" > <
            Property Name= "ConnectionFactory" ref= "redisconnectionfactory"/> <property name= "Keyserializer" >
        <bean class= "Org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name= "ValueSerializer" > <bean class= "org.springframework.data.redis.serializer.JdkSer Ializationredisserializer "/> </property> </bean> <!--cache configuration-<!--<be An id= "Methodcacheinterceptor" class= "Com.mucfc.msm.common.MethodCacheInterceptor" >--> <!--<property Name= "Redisutil" ref= "Redisutil"/>--> <!--</bean >--> <bean id= "Rediscache" class= "Com.drpen G.pengxin.api.cache. Redis. Rediscache "> <property name=" redistemplate "ref=" redistemplate "/> </bean> <bean id=" R Elationcache "class=" Com.drpeng.pengxin.api.cache.redis.RelationCache "> <property name=" redistemplate "ref= "Redistemplate"/> </bean> </beans>
3, Rediscache interface package: Rediscache.java
public class Rediscache {public Logger Logger = Loggerfactory.getlogger (This.getclass ());

    Private redistemplate<serializable, object> redistemplate; /** * Bulk Delete the corresponding value * * @param keys */public void Remove (final String ... keys) {for (stri
        ng Key:keys) {remove (key); 
        }}/** * Bulk Delete key * * @param pattern */public void Removepattern (final String pattern) {
        set<serializable> keys = Redistemplate.keys (pattern);
    if (keys.size () > 0) redistemplate.delete (keys); }/** * Delete the corresponding value * * @param key */public void Remove (final String key) {if (exist
        S (key)) {Redistemplate.delete (key); }}/** * Determine if there is a corresponding value in the cache * * @param key * @return */public Boolean exists (final S
    Tring key) {return Redistemplate.haskey (key);
 }/** * 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 St
        Ring 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 St
        Ring key, Object value, Long expiretime) {Boolean result = false; try {ValueopErations<serializable, object> operations = redistemplate. Opsforvalue ();
            Operations.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.R
    Edistemplate = redistemplate; }

}
4, test for the above cache design
@Service ("Relationservice") public class Relationserviceimpl extends Baseserviceimpl implements Relationservice {@Au
    towired private Relationdao Relationdao;
    @Autowired private Rediscache Rediscache; /* @Autowired Private Relationcache relationcache;*///Set expiration time is one week, each cache must set validity period, later if the data volume is large, ensure that the cache is active user private fi

    nal Long expiretime = 3600*24*5l;
       public int createRelation (Relation Relation) {relationdao.createrelation (Relation);
       Rediscache.set (Relation.getobjectkey (), relation,expiretime);
    return 1;
        } public int updaterelation (Relation Relation) {relationdao.updaterelation (Relation);
        Rediscache.remove (Relation.getobjectkey ());
        Rediscache.set (Relation.getobjectkey (), relation,expiretime);
    return 1; } public Relation queryrelation (Relation Relation) {Relation Relation1 = (Relation) rediscache.get (relation.g
        Etobjectkey ()); if (relation1! = null) {return relatioN1;
            }else {Relation Relation2 = relationdao.queryrelation (Relation);
            if (relation2! = null) {Rediscache.set (Relation.getobjectkey (), relation2,expiretime);
        } return relation2; }
    }
}
Relation class Design:
public class Relation implements serializable{private Long ID;
    AccountId private Long accountId;
    Private String userId; Private Integer DeviceType; Device Type 1, android 2, iOS 3 winphone private String Devicetoken; Device token only the iOS system has private String brand;
    Device manufacturer Private String model;//mobile phone model private Date createtime;

    Private Date UpdateTime;
    Public String Getmodel () {return model;
    } public void Setmodel (String model) {This.model = model;
    } public String Getbrand () {return brand;
    } public void Setbrand (String brand) {This.brand = brand;
    } public Long GetId () {return id;
    } public void SetId (Long id) {this.id = ID;
    } public Long Getaccountid () {return accountId;
    } public void Setaccountid (Long accountId) {this.accountid = AccountId;
    } public String GetUserId () {return userId; } PublIC void Setuserid (String userId) {this.userid = UserId;
    } public Integer Getdevicetype () {return devicetype;
    } public void Setdevicetype (Integer devicetype) {this.devicetype = DeviceType;
    } public String Getdevicetoken () {return devicetoken;
    } public void Setdevicetoken (String devicetoken) {this.devicetoken = Devicetoken;
    Public Date Getcreatetime () {return createtime;
    } public void Setcreatetime (Date createtime) {this.createtime = Createtime;
    Public Date Getupdatetime () {return updatetime;
    } public void Setupdatetime (Date updatetime) {this.updatetime = UpdateTime; Public Relation (Long ID, long accountId, string userId, Integer DeviceType, String Devicetoken, String brand, Date
        Createtime, Date updatetime) {this.id = ID;
        This.accountid = accountId;
        This.userid = userId; This.devicetype =DeviceType;
        This.devicetoken = Devicetoken;
        This.brand = brand;
        This.createtime = Createtime;
    This.updatetime = UpdateTime;
    Public Relation () {} public String GetKey () {return keyprefixs.relation;
    } public String Getobjectkey () {return keyprefixs.relation + accountId + keyprefixs.underline + userId;
 }
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.