Spring-data-redis Storage Objects (redistemplate)

Source: Internet
Author: User

Given the configuration, because the version of the different Jedis API, here is more deceptive, often wrong to start, if the MAVEN project is good to view the source code, if it is a Web project then very troublesome,

<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId>< version>2.0.0</version></dependency><!--Spring-redis--><dependency><groupid> Org.springframework.data</groupid><artifactid>spring-data-redis</artifactid><version> 1.0.0.release</version></dependency>

The

Then gives me the Redis operation tool using the Spring-data-redis package, the principle is object to byte[], and then uses stored, so the Save form is key (Stringkey (byte[] ->string " Span style= "line-height:22.5px;" >)-value (byte[] ->Object )

package com.zhxjz.framework.util.redis;import java.io.serializable;import  org.springframework.dao.dataaccessexception;import  org.springframework.data.redis.connection.redisconnection;import  org.springframework.data.redis.core.rediscallback;import  org.springframework.data.redis.core.redistemplate;import com.zhxjz.framework.util.applicationcontextutil; import com.zhxjz.framework.util.common.serializeutil;public class springredisutil {@ Suppresswarnings ("unchecked") private static redistemplate<serializable, serializable>  redisTemplate =  (redistemplate<serializable, serializable>)   Applicationcontextutil.getbean ("Redistemplate");p Ublic static void save (final String  Key, object value)  {final byte[] vbytes = serializeutil.serialize (value); Redistemplate.execute (new rediscallback<object> ()  {@Overridepublic  objecT doinredis (redisconnection connection) Throws dataaccessexception {connection.set ( Redistemplate.getstringserializer (). Serialize (key),  vbytes); return null;}); Public static <t> t get (final string key, class<t>  ElementType)  {return redistemplate.execute (new rediscallback<t> ()  {@Overridepublic  t doinredis (redisconnection connection) throws dataaccessexception {byte[]  Keybytes = redistemplate.getstringserializer (). Serialize (Key);if  (Connection.exists (keybytes))  {byte[] valuebytes = connection.get (keybytes); @SuppressWarnings ("Unchecked") t value  =  (T)  serializeutil.unserialize (valuebytes); return value;} Return null;}});}}

With Applicationcontextutil and Serializeutil 2 other tools,

Package Com.zhxjz.framework.util;import Org.springframework.beans.beansexception;import Org.springframework.context.applicationcontext;import Org.springframework.context.ApplicationContextAware; Import org.springframework.stereotype.Component; @Componentpublic class Applicationcontextutil implements Applicationcontextaware {private static applicationcontext context; @Overridepublic void Setapplicationcontext ( ApplicationContext context) throws Beansexception {Applicationcontextutil.context = context;} public static ApplicationContext GetContext () {return context;} public static Object Getbean (String beanname) {return Context.getbean (beanname);}}
package com.zhxjz.framework.util.common;import java.io.bytearrayinputstream;import  java.io.bytearrayoutputstream;import java.io.objectinputstream;import java.io.objectoutputstream; Public class serializeutil {public static byte[] serialize (Object object)  {ObjectOutputStream oos = null; bytearrayoutputstream baos = null;try {//  Serialization baos = new  Bytearrayoutputstream (); Oos = new objectoutputstream (BAOs); Oos.writeobject (object);byte[]  Bytes = baos.tobytearray (); return bytes;}  catch  (exception e)  {throw new runtimeexception (E.getmessage (),  e);}} Public static object unserialize (byte[] bytes)  {bytearrayinputstream bais =  null;try {//  deserialization Bais = new bytearrayinputstream (bytes);objectinputstream  Ois = new objectinputstream (Bais); Return ois.readobject ();}  catch  (exception e)  {throw new runtimeexception (E.getmessage (),  e);}}

And then give the Springbean configuration,

<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xmlns:p="/HTTP/ www.springframework.org/schema/p "xmlns:context=" Http://www.springframework.org/schema/context "xsi: Schemalocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema /context/spring-context-4.0.xsd "><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><bean id=" JedisconNectionfactory "class=" Org.springframework.data.redis.connection.jedis.JedisConnectionFactory "><property  name= "HostName"  value= "${redis.hostname}"  /><property name= "Port"  value= "${ Redis.port} " /><property name=" password " value=" ${redis.password} " /><property  name= "Poolconfig"  ref= "Jedispoolconfig"  /></bean><bean id= "RedisTemplate"  class= "Org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref= " Jedisconnectionfactory " /></beans>

<import resource= "Classpath:/springredis.xml"/>

Here's redis.properties.

#redis configredis.pool.maxactive=100redis.pool.maxidle=20redis.pool.maxwait=1000redis.pool.testonborrow= trueredis.hostname=127.0.0.1redis.port=6379redis.password=

Don't forget to register this properties file to Propertyplaceholderconfigurer

Usage:

Write a controller to test:

Package Com.zhxjz.controller.testredis;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.responsebody;import Com.zhxjz.framework.util.redis.SpringRedisUtil; Import Com.zhxjz.model.testredis.TESTREDIS; @Controller @requestmapping ("/testredis") public class Testrediscontroller {@RequestMapping ("/test.do") @ResponseBodypublic String Test (Testredis Testredis) { Springredisutil.save ("MyStr", Testredis); return Springredisutil.get ("MyStr", Testredis.class). toString ();}}

Finally, give me the model.

package com.zhxjz.model.testredis;public  Class testredis implements java.io.serializable {private static final long  serialVersionUID = 1L; String teststr;int testint;boolean testbool;public string getteststr ()  {return  teststr;} Public void setteststr (STRING&NBSP;TESTSTR)  {this.teststr = teststr;} Public int gettestint ()  {return testint;} Public void settestint (Int testint)  {this.testint = testint;} Public boolean istestbool ()  {return testbool;} Public void settestbool (Boolean testbool)  {this.testbool = testbool;} Public string tostring ()  {return this.testStr +  "|"  + this.testInt +  "|"  + this.testbool;}} 

Visit: Http://localhost:8080/demo/testredis/test.do?testStr=testStr1&&testInt=1234&&testBool=true

View client:

Attention:

Because the model needs to be converted to byte[], here the model must be implements Java.io.Serializable, otherwise it will be an error.

Spring-data-redis Storage Objects (redistemplate)

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.