Spring Boot Tutorial VII: Integrated REDIS

Source: Internet
Author: User
Tags redis serialization spring boot tutorial

Redis is commonly used in the development of caching, user Rights Management, Message Queuing and other functions, today to learn about the Springboot integrated Redis, Redis installation can be Baidu to start, here only the implementation of the Code.
First, introduce dependencies:

<!--adding Redis Support-
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.2.8.release</version >
        </dependency>

Renaming the ReadProperties we created earlier in the read configuration file to Redisutil, the code changes as follows:

/** * @Package: Com.springboot.utils * @ClassName: Redisutil * @Description: Redis Tool class * @Author Shuyu.wang * @Date 2017- 12-07 12:18 **/@EnableConfigurationProperties ({redis.class}) @Component public class Redisutil {@Autowired priv

    Ate Redis Redis;
    public void Read () {System.out.println (Redis.getip ());

    }/** * Non-tiled link pool */private jedispool jedispool; /** * Non-tiled connection pool initialization */private Jedispool Initialpool () {//Pool basic configuration jedispoolconfig config = new J
        Edispoolconfig ();
        Config.setmaxtotal (Redis.getmaxtotal ());
        Config.setmaxidle (Redis.getmaxidle ());
        Config.setmaxwaitmillis (Redis.getmaxactive ());
        Config.settestonborrow (Redis.gettestonborrow ());
        Config.settestonreturn (Redis.gettestonreturn ());
        Jedispool = new Jedispool (config, Redis.getip (), Redis.getport ());

    return jedispool; }/** * */private synchronized void Poolinit in multi-threaded environment ({if (Jedispool = = null) {Initialpool (); }}/** * Non-slice client link synchronization get non-tile Jedis instance * * @return Jedis * */@SuppressWarnings ("Depreca
        tion ") Public synchronized Jedis Getjedis () {if (Jedispool = = null) {poolinit ();
        } Jedis Jedis = null;
                try {if (Jedispool! = null) {Jedis = Jedispool.getresource ();
            Jedis.auth (password);
            }} catch (Exception e) {System.out.println ("throw error");
            E.printstacktrace ();
        Release Jedis object Jedispool.returnbrokenresource (Jedis); } finally {//return connection pool if (Jedis! = NULL && Jedispool! = null) {JEDISPOOL.R

            Eturnresource (Jedis);

    }} return Jedis;
 }


}

Another new tool class that implements serialization and deserialization:

/** * Serialization Tool class * @author Shuyu.wang * */public class Serializeutil {/** * serialization * @param value * @ret URN */public static byte[] Serialize (Object value) {if (value = = null) {throw new Nullpo

        Interexception ("Can ' t serialize null");

        } byte[] RV = null;

        Bytearrayoutputstream BOS = NULL;

        ObjectOutputStream OS = null;

            try {bos = new Bytearrayoutputstream ();

            OS = new ObjectOutputStream (BOS);

            Os.writeobject (value);

            Os.close ();

            Bos.close ();

        RV = Bos.tobytearray ();

        } catch (IOException e) {throw new IllegalArgumentException ("Non-serializable object", e);

                } finally {try {if (OS! = null) os.close ();

            if (BOS! = null) bos.close (); } catch (Exception E2) {e2.printstacktrace ();

            }} return RV; }/** Deserialization * @param bytes * @return * * * public static Object unserialize (byte[] bytes) {Ob

        Ject RV = null;

        Bytearrayinputstream bis = null;

        ObjectInputStream is = null;

                try {if (bytes! = null) {bis = new Bytearrayinputstream (bytes);

                is = new ObjectInputStream (bis);

                RV = Is.readobject ();

                Is.close ();

            Bis.close ();

        }} catch (Exception e) {e.printstacktrace ();

                } finally {try {if (is! = null) is.close ();

            if (bis! = null) bis.close ();

            } catch (Exception E2) {e2.printstacktrace ();

    }} return RV;
 }

}

Also create a new Redis package, create a new Redisservice interface class, and the corresponding implementation class Redisserviceimpl;
code, respectively;

/** * @ClassName: Redisdao * @Description: Redis interface * @author Shuyu.wang * @date November 23, 2017 pm 3:55:53 * @version V1

    .0 */public interface Redisservice {public void setString (string key, int seconds, string value);

    public boolean exist (String key); /** * Storage String * @param key * @param param * * Public <T> Boolean setString (string key, Strin

    g param);

    /** * Get stringֵ* @param key * @return String */public string getString (string key); /** * Storage entity class * @param key * @param bean * * Public <T> Boolean Setbean (String key, Object Bean

    );

    /** * Get entity class * @param key * @return T */public <T> T Getbean (String key); /** * Store list * @param key * @param list */Public <T> Boolean setlist (String key, list<t

    > list); /** * Get list * @param key * @return list */public <T> list<t> GetList (String key); /** * Store Map * @param key * @param map * * Public <T> Boolean setmap (String key, Map<strin

    G, t> map); /** * Get map * @param key * @return Map */public <T> map<string, t> getmap (String key)

    ;
    /** * @param key * @return */public boolean del (String key);  /** * @param key * @param num * @return */Public <T> Boolean Setinteger (String key, Integer

    NUM);

    /** * @param key * @return * */Public integer getsetinteger (String key, Integer num);


    /** * @param key * @return */public Integer Getinteger (String key); /** * Non-serialized storage * @param key * @param map * @return */Public <T> Boolean Sethash (String K

    EY, map<string, string> Map); /** gets the key value of all maps in key * @param key * @return */public map<string, string> Getallhash (String Key); /** Gets the value collection of Key=fields in the map in key * @param key * @param fields * @return */Public list<string


    > Gethashm (String Key, String ... fields); 
    /** * @Title: Login * @Description: TODO * @param userId * @param second * @return String return token


    * @throws */Public String Login (string userId, int second);

    Public Boolean Validate (String token);

    public void Logout (String token);

public string GetUserId (string token); }
/** * @ClassName: Redisdaoimpl * @Description: TODO * @author Shuyu.wang * @date October 19, 2017 pm 2:54:39 * @version V 1.0 */@Service public class Redisserviceimpl implements Redisservice {private static final String VIRTUAL_COURSE_PR
    EX = "Lc_vc_";

    @Autowired private Redisutil Redisutil;


    private static final String return_ok= "OK"; /** * * @param key * @return */public string Buildkey (string key) {return virtual_cours
    E_prex + key; }/* * (NON-JAVADOC) * * @see com.shuyu.cache.redisdao#setstring (java.lang.String, int, * JAVA.L Ang. String) */@Override public void setString (string key, int seconds, string value) {Jedis Jedis = red
        Isutil.getjedis ();

    Jedis.setex (Buildkey (key), seconds, value);
    }/* * (NON-JAVADOC) * * @see com.shuyu.cache.redisdao#exist (java.lang.String) */@Override public boolean exist (String key) {Jedis Jedis = Redisutil.getjedis ();
        String bkey = Buildkey (key);
        if (Jedis = = NULL | |!jedis.exists (bkey)) {return false;
    } return true; }/** * * @param key * @param param */@Override public <T> boolean setString (stri
        ng key, String param) {Jedis Jedis = Redisutil.getjedis ();
        String bkey = Buildkey (key);
        String set = null;
        System.out.println ("jedis==============" +jedis);
        Set = Jedis.set (Bkey.getbytes (), serializeutil.serialize (param));
        if (!set.isempty () && (RETURN_OK). Equals (set)) {RETURN true;
        } else {return false; }}/** *ȡstringֵ* * @param key * @return String */@Override public Strin
        G getString (String key) {Jedis Jedis = Redisutil.getjedis ();
        String bkey = Buildkey (key);
        String retru = null; if (Jedis = = NULL | |!jediS.exists (Bkey)) {return null;
        } byte[] in = Jedis.get (Bkey.getbytes ());
        Retru = Serializeutil.unserialize (in). ToString ();

    return retru; }/** * * @param key * @param bean */@Override public <T> boolean Setbean (String
        Key, Object Bean) {String bkey = Buildkey (key);
        Jedis Jedis = Redisutil.getjedis ();
        String set = null;
        Set = Jedis.set (Bkey.getbytes (), serializeutil.serialize (Bean));
        if (!set.isempty () && (RETURN_OK). Equals (set)) {RETURN true;
        } else {return false;
    }}/** * * @param key * @return T */@SuppressWarnings ("unchecked") @Override
        Public <T> T Getbean (String key) {Jedis Jedis = Redisutil.getjedis ();
        String bkey = Buildkey (key);
        T bean = null; if (Jedis = = NULL | |!jedis.exists (bkey.getbytes ())) {return nUll
        } byte[] in = Jedis.get (Bkey.getbytes ());
        Bean = (T) serializeutil.unserialize (in);

    return bean; }/** * @param key * @param list */@Override public <T> Boolean setlist (String key, Lis
        T<t> list) {Jedis Jedis = Redisutil.getjedis ();
        String bkey = Buildkey (key);
        String set = null;
        Set = Jedis.set (Bkey.getbytes (), serializeutil.serialize (list));
        if (!set.isempty () && (RETURN_OK). Equals (set)) {RETURN true;
        } else {return false;
    }}/** * * @param key * @return list */@SuppressWarnings ("unchecked") @Override
        Public <T> list<t> getList (String key) {Jedis Jedis = Redisutil.getjedis ();
        String bkey = Buildkey (key);
        list<t> list = null;
        if (Jedis = = NULL | |!jedis.exists (bkey.getbytes ())) {return null;
      }  byte[] in = Jedis.get (Bkey.getbytes ());
        List = (list<t>) serializeutil.unserialize (in);

    return list; }/** * * @param <T> * @param key */@Override public <T> boolean Setmap (Str
        ing key, map<string, t> Map) {String bkey = Buildkey (key);
        Jedis Jedis = Redisutil.getjedis ();
        String set = null;
        Set = Jedis.set (Bkey.getbytes (), serializeutil.serialize (map));
        if (!set.isempty () && (RETURN_OK). Equals (set)) {RETURN true;
        } else {return false;
    }}/** * * @param key * @return Map */@Override @SuppressWarnings ("unchecked")
        Public <T> map<string, t> getmap (String key) {string bkey = Buildkey (key);
        Jedis Jedis = Redisutil.getjedis ();
        map<string, t> map = null; if (Jedis = = NULL | |!jedis.exists (bkey.getbytes ())) {return nulL
        } byte[] in = Jedis.get (Bkey.getbytes ());
        Map = (map<string, t>) serializeutil.unserialize (in);
    return map;
        } @Override public Boolean del (string key) {string bkey = Buildkey (key);
        Jedis Jedis = Redisutil.getjedis ();
        Long del = (long) 0;
        if (Jedis = = NULL | |!jedis.exists (bkey.getbytes ())) {return false;
        } del = Jedis.del (Bkey.getbytes ());
        if (Del > 0) {return true;
    } return false; } @Override Public <T> boolean Setinteger (String key, Integer num) {Jedis Jedis = Redisutil.getjed
        Is ();
        String bkey = Buildkey (key);
        String set = null;
        Set = Jedis.set (Bkey, string.valueof (num));
        if (!set.isempty () && (RETURN_OK). Equals (set)) {RETURN true;
        } else {return false; }} @Override public Integer Getsetinteger (String key, INteger num) {String bkey = Buildkey (key);
        Jedis Jedis = Redisutil.getjedis ();
        String set = null;
        Set = Jedis.getset (Bkey, string.valueof (num));
    Return integer.valueof (set);
        } @Override Public Integer Getinteger (string key) {string bkey = Buildkey (key);
        Jedis Jedis = Redisutil.getjedis ();
        String set = null;
        if (Jedis = = NULL | |!jedis.exists (bkey)) {return null;
        } set = Jedis.get (Bkey);
    Return integer.valueof (set); } @Override Public <T> boolean Sethash (String key, map<string, string> Map) {string bkey = b
        Uildkey (key);
        Jedis Jedis = Redisutil.getjedis ();
        String hmset = null;
        Hmset = Jedis.hmset (bkey, map);
        if (!hmset.isempty () && (RETURN_OK). Equals (Hmset)) {RETURN true;
        } else {return false; }} @Override public map<string, string>Getallhash (String key) {string bkey = Buildkey (key);
        Jedis Jedis = Redisutil.getjedis ();
        map<string, string> map = null;
        if (Jedis = = NULL | |!jedis.exists (bkey)) {return null;
        } map = Jedis.hgetall (bkey);
    return map; } @Override Public list<string> Gethashm (string key, String ... fields) {string bkey = Buildkey (key
        );
        Jedis Jedis = Redisutil.getjedis ();
        list<string> list = null;
        if (Jedis = = NULL | |!jedis.exists (bkey)) {return null;
        } list = Jedis.hmget (Bkey, fields);
    return list; }/* * (NON-JAVADOC) * * @see com.hc.redis.dao.redisdao#login (java.lang.String, int) */@Ove
        Rride public String Login (string userId, int second) {Jedis Jedis = Redisutil.getjedis ();
        String token = Buildkey (userId); if (Jedis = = NULL | |!jedis.exists (token)) {//tokenProduction rules custom ֵjedis.setex (token, second, userId);
        } else {Jedis.expire (token, second);
    } return token;
         } @Override public Boolean validate (String token) {Jedis Jedis = Redisutil.getjedis ();
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.