These days are fine, the previous learning of the Redis code to tidy up, nonsense not much to say, on the steps.
1, Pom.xml the introduction of resources;
<dependency> <groupId>org.springframework.data</groupId> <artifactId> spring-data-redis</artifactid> <version>1.7.0.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactid>jedis</ artifactid> <version>2.8.0</version> </dependency>
2, configure Redis configuration file, here only configure a single-point database, the following will introduce the configuration of Redis cluster, here is not much to say;
Spring-redis.xml configuration:
<!--read profile information--<context:property-placeholder ignore-unresolvable= "true" location= "Classpath:*.propertie S "/> <!--Redis configuration--<bean id=" Jedispoolconfig "class=" Redis.clients.jedis.JedisPoolConfig "> <property name= "Maxtotal" value= "${redis.maxactive}"/> <property name= "Maxidle" value= "${redis.maxIdle}" /> <property name= "Maxwaitmillis" value= "${redis.maxwaitmillis}"/> <property name= "TestOnBorro W "value=" true "/> </bean> <!--redis Single-node database connection configuration-<bean id=" jedisconnectionfactory "class=" or G.springframework.data.redis.connection.jedis.jedisconnectionfactory "> <property name=" hostName "value=" ${ Redis.host} "/> <property name=" port "value=" ${redis.port} "/> <property name=" password "value=" ${redis.password} "/> <property name=" poolconfig "ref=" Jedispoolconfig "/> </bean> <!--red Istemplate configuration, Redistemplate isMore operations on Jedis for Redis operations, encapsulation makes operation easier-<bean id= "Redistemplate" class= " Org.springframework.data.redis.core.StringRedisTemplate "> <property name=" connectionfactory "ref=" Jedisconnectionfactory "/> </bean>
Redis.properties File configuration:
#redis的服务器地址redis. host= here Write your Ip#redis service port redis.port=6379# password redis.password= here write your password # link database redis.default.db=0# The client time-out unit is milliseconds redis.timeout=100000# maximum number of connections redis.maxactive=300# maximum idle redis.maxidle=100# maximum connection wait time Redis.maxwaitmillis =1000
3, then, the specific implementation of the Code;
Serialization and deserialization tool classes:
Public classSerializerutil {/*** Serialization *@paramObject *@return */ Public Static byte[] Serializeobj (Object object) {ObjectOutputStream Oos=NULL; Bytearrayoutputstream BAOs=NULL; Try{BAOs=NewBytearrayoutputstream (); Oos=NewObjectOutputStream (BAOs); Oos.writeobject (object); byte[] bytes =Baos.tobytearray (); returnbytes; } Catch(Exception e) {Throw NewRuntimeException ("Serialization failed!"), E); } } /*** Deserialization *@parambytes *@return */ Public StaticObject Deserializeobj (byte[] bytes) { if(bytes = =NULL){ return NULL; } Bytearrayinputstream Bais=NULL; Try{Bais=Newbytearrayinputstream (bytes); ObjectInputStream Ois=NewObjectInputStream (Bais); returnOis.readobject (); } Catch(Exception e) {Throw NewRuntimeException ("Deserialization failed!"), E); } }}
Operation implementation class, where only 3 implementation classes are provided, others can be implemented according to their own needs:
@Component Public classRediscache {@ResourcePrivateRedistemplate<string, string>redistemplate; /*** Add Cached Data *@paramKey *@paramobj *@param<T> *@return * @throwsException*/ Public<T>BooleanPutcache (String key, T obj)throwsException {Final byte[] Bkey =key.getbytes (); Final byte[] Bvalue =serializerutil.serializeobj (obj); Booleanresult = Redistemplate.execute (NewRediscallback<boolean>() {@Override PublicBoolean Doinredis (redisconnection connection)throwsDataAccessException {returnconnection.setnx (Bkey, bvalue); } }); returnresult; } /*** Add cached data to set cache expiration time *@paramKey *@paramobj *@paramExpiretime *@param<T> *@throwsException*/ Public<T>voidPutcachewithexpiretime (String key, T obj,Final LongExpiretime)throwsException {Final byte[] Bkey =key.getbytes (); Final byte[] Bvalue =serializerutil.serializeobj (obj); Redistemplate.execute (NewRediscallback<boolean>() {@Override PublicBoolean Doinredis (redisconnection connection)throwsDataAccessException {Connection.setex (Bkey, Expiretime, bvalue); return true; } }); } /*** Cache data based on key *@paramKey *@param<T> *@return * @throwsException*/ Public<T> T GetCache (FinalString key)throwsException {byte[] result = Redistemplate.execute (Newrediscallback<byte[]>() {@Override Public byte[] Doinredis (redisconnection connection)throwsDataAccessException {returnConnection.get (Key.getbytes ()); } }); if(Result = =NULL) { return NULL; } return(T) serializerutil.deserializeobj (result); }}
4, test code;
@Test Public voidTest7 ()throwsexception{List<String> list =NewArraylist<string>(); List.add ("Test List"); List.add ("Test List2"); Map<String,Object> map =NewHashmap<string, object>(); Map.put ("test*", "Test data"); Map.put ("Test Data", "what"); Map.put ("Listtest", list); Rediscache.putcache ("TestMap", map); Map<String,Object> Mapresult = Rediscache.getcache ("TestMap"); System.out.print (Mapresult.tostring ()); }
Results:
5, OK, all normal. PS: Interested students can go to see the Redis source code, very good!
Spring + Jedis Integrated Redis