Spring Boot Redis Integrated Configuration

Source: Internet
Author: User
Tags object object redis serialization

When Spring Boot is familiar, it's easy to integrate an external extension, and it's easy to integrate with Redis, see the following steps to configure: First, add pom dependency

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId> Spring-boot-starter-redis</artifactid>
        </dependency>
Ii. creation of Redisclient.java

Note that this class contains the package

Package Org.springframework.data.redis.connection.jedis;
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;

Import java.io.UnsupportedEncodingException;
Import Org.apache.commons.lang3.StringUtils;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.Protocol;

Import redis.clients.jedis.exceptions.JedisException; /** * Tool Class Redisclient * Because getting jedispool in this class is called protected-modified method in Jedisconnectionfactory fetchjedisconnector () *  So the class needs to be in the same package as Jedisconnectionfactory * * @author Tan Hongyu (CSDN catoop) * @create April 9, 2017 */public class Redisclient

    {private static Logger Logger = Loggerfactory.getlogger (Redisclient.class);

    Private Jedisconnectionfactory Factory;
        Public redisclient (Jedisconnectionfactory factory) {super ();
    This.factory = Factory; }/** * Put operation (storageSerialized object) + Effective time * * @param key * @param value * @return */public void PutObject (final String K EY, final Object value, final int cacheseconds) {if (Stringutils.isnotblank (key)) {Redistemplete (key
                    , new redisexecute<object> () {@Override public Object doinvoker (Jedis Jedis) { 
                    try {Jedis.setex (key.getbytes (Protocol.charset), Cacheseconds, serialize (value));
                } catch (Unsupportedencodingexception e) {} return null;
        }
            }); }}/** * Get operation (get serialized object) * * @param key * @return */public object GetObject (final String key) {return Redistemplete (key, New redisexecute<object> () {@Override publi C Object Doinvoker (Jedis Jedis) {try {byte[] Bytekey = Key.getbytes (Protocol.charset);
                    byte[] Bytevalue = Jedis.get (Bytekey);
                    if (bytevalue! = null) {return deserialize (bytevalue);
                }} catch (Unsupportedencodingexception e) {return null;
            } return null;
    }
        }); }/** * Setex operation * * @param key * key * @param value * values * @pa Ram Cacheseconds * Timeout time, 0 is not timed out * @return */public string Set (final string key, final string Value, final int cacheseconds) {return Redistemplete (key, New redisexecute<string> () {@Overrid E public String Doinvoker (Jedis Jedis) {if (cacheseconds = = 0) {return j
                Edis.set (key, value);
            } return Jedis.setex (Key, cacheseconds, value);
    }
        });
}

    /**     * Get Operation * * @param key * @return Value */public string get (final string key {return Redistemplete (key, New redisexecute<string> () {@Override public String D
                Oinvoker (Jedis Jedis) {String value = Jedis.get (key); return Stringutils.isnotblank (value) &&! " Nil ". Equalsignorecase (value)?
            Value:null;
    }
        }); }/** * del operation * * @param key * key * @return * * Public long del (final Str ing key) {return Redistemplete (key, New redisexecute<long> () {@Override public Lon
            G Doinvoker (Jedis Jedis) {return Jedis.del (key);
    }
        }); }/** * Get resources * * @return * @throws jedisexception */public Jedis getresource () throws
        jedisexception {Jedis Jedis = null; try {Jedis = FACTory.fetchjedisconnector ();
            } catch (Jedisexception e) {logger.error ("getresource.", e);
            Returnbrokenresource (Jedis);
        Throw e;
    } return Jedis; }/** * Get resources * * @return * @throws jedisexception */public Jedis Getjedis () throws Jed
    isexception {return getresource (); /** * Return Resources * * @param Jedis * @param isbroken * * public void Returnbrokenresource (Jed
        is Jedis) {if (Jedis! = null) {jedis.close (); }}/** * Frees resources * * @param Jedis * @param isbroken * * * public void Returnresource (Jed
        is Jedis) {if (Jedis! = null) {jedis.close (); }}/** * Operation Jedis Client Template * * @param key * @param execute * @return */Public &lt ;
        R> R redistemplete (String key, redisexecute<r> execute) {Jedis Jedis = null;try {Jedis = GetResource ();
            if (Jedis = = null) {return null;
        } return Execute.doinvoker (Jedis);
        } catch (Exception e) {logger.error ("operator Redis API fail,{}", key, E);
        } finally {Returnresource (Jedis);
    } return null;
     }/** * Feature brief: Serialization of entity beans. * * @param source * The entity to be converted * @return byte array after conversion * @throws Exception */public stat
        IC byte[] Serialize (Object source) {Bytearrayoutputstream byteout = null;
        ObjectOutputStream objout = null;
            try {byteout = new Bytearrayoutputstream ();
            Objout = new ObjectOutputStream (byteout);
            Objout.writeobject (source);
        Objout.flush ();
        } catch (IOException e) {e.printstacktrace (); } finally {try {if (null! = objout) {objout.clOSE ();
            }} catch (IOException e) {objout = null;
    }} return Byteout.tobytearray ();
     }/** * Feature brief: Deserializes a byte array into an entity bean. * * @param source * A byte array to deserialize * @return the deserialized entity bean * @throws Exception */P
        Ublic static Object Deserialize (byte[] source) {ObjectInputStream Objin = null;
        Object retVal = null;
            try {bytearrayinputstream Bytein = new Bytearrayinputstream (source);
            Objin = new ObjectInputStream (Bytein);
        RetVal = Objin.readobject ();
        } catch (Exception e) {e.printstacktrace ();
                } finally {try {if (null! = Objin) {objin.close ();
            }} catch (IOException e) {Objin = null;
    }} return retVal; } interface redisexecute<t> {T DoinvokER (Jedis jedis);
 }
}
Iii. Creating a Redis configuration class

Redisconfig.java

Package Com.shanhy.example.redis;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
Import org.springframework.data.redis.connection.jedis.RedisClient;
Import Org.springframework.data.redis.core.RedisTemplate;

Import Org.springframework.data.redis.serializer.StringRedisSerializer; /** * Redis Configuration * * @author Tan Hongyu (CSDN catoop) * @create September 12, 2016 */@Configuration public class Redisconfig {@B EAN public redistemplate<string, object> redistemplate (Jedisconnectionfactory factory) {REDISTEMPLATE&L T
        String, object> template = new redistemplate<string, object> ();
        Template.setconnectionfactory (Factory);
        Template.setkeyserializer (New Stringredisserializer ());
        Template.setvalueserializer (New Redisobjectserializer ());
        Template.afterpropertiesset ();
    return template; } @BEAN public redisclient redisclient (Jedisconnectionfactory Factory) {return new redisclient (factory);
 }
}

Redisobjectserializer.java

Package Com.shanhy.example.redis;
Import Org.springframework.core.convert.converter.Converter;
Import Org.springframework.core.serializer.support.DeserializingConverter;
Import Org.springframework.core.serializer.support.SerializingConverter;
Import Org.springframework.data.redis.serializer.RedisSerializer;

Import org.springframework.data.redis.serializer.SerializationException; /** * Implementing the object's serialization interface * @author Tan Hongyu (365384722) * @myblog http://blog.csdn.net/catoop/* @create April 9, 2017 * * Public Class Redisobjectserializer implements redisserializer<object> {private converter<object, byte[]> serial
    Izer = new Serializingconverter ();

    Private converter<byte[], object> deserializer = new Deserializingconverter ();

    Static final byte[] Empty_array = new Byte[0];
        @Override public Object Deserialize (byte[] bytes) {if (IsEmpty (bytes)) {return null;
       } try {return Deserializer.convert (bytes); } catch (Exception ex) {throw new SerializationException ("Cannot deserialize", ex); }} @Override public byte[] Serialize (Object object) {if (object = = null) {return EMPTY
        _array;
        } try {return Serializer.convert (object);
        } catch (Exception ex) {return empty_array;
    }} Private Boolean IsEmpty (byte[] data) {return (data = = NULL | | data.length = = 0);
 }

}
Iv. Creating test methods

Put the following code in a controller.

    @Autowired
    Private redistemplate<string, object> redistemplate;

    /** *
     Cache Test * *
     @return
     * @author  shanhy
     * @create  September 12, 2016
    */@ Requestmapping ("/redistest") public
    String redistest () {
        try {
            redistemplate.opsforvalue (). Set (" Test-key "," Redis test Content ", 2, timeunit.seconds);//cache is valid for 2 seconds

            logger.info (" read data from Redis: "+ redistemplate.opsforvalue ( ). Get ("Test-key"). toString ());

            TimeUnit.SECONDS.sleep (3);

            Logger.info ("Wait 3 seconds to attempt to read expired data:" + redistemplate.opsforvalue (). Get ("Test-key"));
        } catch (Interruptedexception e) {
            e.printstacktrace ();
        }

        return "OK";
    }
v. Configuration file configuration Redis

Application.yml

Spring:
  # Redis configuration
  redis:
    host:192.168.1.101
    port:6379
    Password:
    # Connection time-out (milliseconds)
    timeout : 10000
    Pool:
      max-idle:20
      min-idle:5
      max-active:20
      max-wait:2

This completes the Redis configuration, and the redistemplate can be used normally.

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.