Springboot Integrated Redis basic Operation class

Source: Internet
Author: User

1 Pom.xml Add Dependency

<dependency><groupId>org.springframework.boot</groupId><artifactId> spring-boot-starter-redis</artifactid><version>1.4. 7. Release</version></dependency>

2 Create a new configuration class

import java.io.Serializable;    Import Java.lang.reflect.Method;  Import Org.springframework.cache.CacheManager;  Import Org.springframework.cache.annotation.CachingConfigurerSupport;  Import org.springframework.cache.annotation.EnableCaching;  Import Org.springframework.cache.interceptor.KeyGenerator;  Import Org.springframework.context.annotation.Bean;  Import org.springframework.context.annotation.Configuration;  Import Org.springframework.data.redis.cache.RedisCacheManager;  Import Org.springframework.data.redis.connection.RedisConnectionFactory; Import Org.springframework.data.redis.core.redistemplate;import Org.springframework.data.redis.serializer.jdkserializationredisserializer;import    Org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration @EnableCaching Public classRedisconfig extends Cachingconfigurersupport {@Bean Publickeygenerator Bilikeygenerator () {return NewKeygenerator () {@Override PublicObject Generate (Object target, Method method, Object ...)params) {StringBuilder sb=NewStringBuilder ();                  Sb.append (Target.getclass (). GetName ());                  Sb.append (Method.getname ());  for(Object obj:params) {sb.append (obj.tostring ()); }                  returnsb.tostring ();        }          }; } @Bean PublicCacheManager CacheManager (@SuppressWarnings ("Rawtypes") Redistemplate redistemplate) {return NewRediscachemanager (redistemplate); } @Bean PublicRedistemplate<serializable, serializable>redistemplate (redisconnectionfactory redisconnectionfactory) {redistemplate<serializable, serializable> redistemplate =NewRedistemplate<serializable, serializable>();          Redistemplate.setconnectionfactory (redisconnectionfactory); Redistemplate.setkeyserializer (NewStringredisserializer ()); In other projects, keep the serialization uniform otherwise there will be exception Redistemplate.setvalueserializer with different value types (NewJdkserializationredisserializer ()); returnredistemplate; }  }

3 attached Redisservice

import java.io.serializable;import java.util.list;import java.util.set;import java.util.concurrent.TimeUnit; Import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.data.redis.core.hashoperations;import org.springframework.data.redis.core.ListOperations; Import Org.springframework.data.redis.core.redistemplate;import Org.springframework.data.redis.core.setoperations;import org.springframework.data.redis.core.ValueOperations; Import Org.springframework.data.redis.core.zsetoperations;import Org.springframework.stereotype.Service; @Service  Public classRedisservice {@AutowiredPrivateredistemplate redistemplate; /** * Write Cache * @param key * @param value * @return*/     PublicBooleanSet(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 (); }        returnresult; }    /** * Write Cache Set aging time * @param key * @param value * @return*/     PublicBooleanSet(Final String 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 (); }        returnresult; }    /** * Bulk Delete the corresponding value * @param keys*/     Public voidRemove (final String ... keys) { for(String key:keys) {remove (key); }    }    /** * Bulk Delete key * @param pattern*/     Public voidRemovepattern (final String pattern) {Set<Serializable> keys =Redistemplate.keys (pattern); if(Keys.size () >0) Redistemplate.delete (keys); }    /** * Delete the corresponding value * @param key*/     Public voidRemove (final String key) {if(Exists (key)) {Redistemplate.delete (key); }    }    /** * To determine if there is a corresponding value in the cache * @param key * @return*/     PublicBoolean exists (final String key) {returnRedistemplate.haskey (key); }    /** * Read cache * @param key * @return*/     PublicObjectGet(final String key) {Object result=NULL; Valueoperations<serializable, object> operations =Redistemplate.opsforvalue (); Result= Operations.Get(key); returnresult; }    /** * Hash Add * @param key * @param hashkey * @param value*/     Public voidHmset (String key, Object HashKey, Object value) {hashoperations<string, Object, object> hash =Redistemplate.opsforhash ();    Hash.put (Key,hashkey,value); }    /** * Hash FETCH data * @param key * @param hashkey * @return*/     PublicObject Hmget (String key, Object HashKey) {hashoperations<string, Object, object> hash =Redistemplate.opsforhash (); returnHash.Get(Key,hashkey); }    /** * list Add * @param k * @param v*/     Public voidLpush (String k,object v) {listoperations<string, object> list =redistemplate.opsforlist ();    List.rightpush (K,V); }    /** * list Get * @param k * @param l * @param L1 * @return*/     PublicList<object> Lrange (String K,LongLLongL1) {listoperations<string, object> list =redistemplate.opsforlist (); returnList.range (K,L,L1); }    /** * Set Add * @param key * @param value*/     Public voidAdd (String key,object value) {setoperations<string, object>Set=Redistemplate.opsforset (); Set. Add (Key,value); }    /** * Collection gets * @param key * @return*/     PublicSet<object>setmembers (String key) {setoperations<string, object>Set=Redistemplate.opsforset (); return Set. Members (key); }    /** * Ordered collection Add * @param key * @param value * @param scoure*/     Public voidZadd (String key,object value,Doublescoure) {zsetoperations<string, object> zset =Redistemplate.opsforzset ();    Zset.add (key,value,scoure); }    /** * Order collection Get * @param key * @param scoure * @param scoure1 * @return*/     PublicSet<object> Rangebyscore (String key,DoubleScoure,Doublescoure1) {zsetoperations<string, object> zset =Redistemplate.opsforzset (); returnZset.rangebyscore (Key, Scoure, Scoure1); }}

Springboot Integrated Redis basic Operation class

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.