Redis simulation session in distributed environment

Source: Internet
Author: User
Tags json redis

First, why use Redis.

Because of the distribution of different servers, if you normally store the session, then your session will be saved on a server, if your next request is not to access the server, it will occur when the session is not read

implementation of Redis storage:

The first is implemented using container extensions, typically through container plug-ins, such as Tomcat-based Tomcat-redis-session-manager, jetty-based Jetty-session-redis, and so on. The benefits are transparent to the project, no code changes are required, but TOMCAT8 is not currently supported. Personally feel that because of too much reliance on containers, once the replacement of containers or containers upgrade, it will have to re-come. And the code is not in the project, and the maintenance of the developer is a hassle.

The second is the custom Session management tool class, which is flexible enough to be implemented according to your own needs, but requires additional development time

The third is the use of the framework of the session management tools, such as Spring-session,shiro, can be understood to replace the servlet set of Session management, do not rely on the container, without changing the code. If you are using spring-session, use the Spring-data-redis set of connection pools, prefect, but only if you have to use the spring framework. As for Shiro, it is a very mature, powerful and easy-to-use security framework that costs more to learn than spring-session.

let's look at the implementation of the second approach

It is important to note that the frontend uses Ajax to log in, because after the simulation session information is stored in Redis, it is necessary to store the UserID and token locally as the user's identity, and through this identity to Redis to verify that the user is logged in, To obtain user login information in Redis, but multiple systems in the distributed system correspond to multiple domain, so the UserID and token generated by the login module are used by each system, and each system must generate its own cookie information. The Java side cannot generate a cookie for each system so a cookie can only be generated for each system in the front end with an IFRAME

Here is the detailed code

Configuration of Redis:

<?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:context= "Http://www.springframework.org/schema/context" xmlns:mongo= "Http://www.springframework.org/schema/data/mongo" xmlns:p= "http://www.springframework.org/schema/p "Xsi:schemalocation=" Http://www.springframework.org/schema/context Http://www.springframework.org/schema /context/spring-context.xsd Http://www.springframework.org/schema/data/mongo HTTP://WWW.SPRINGFR Amework.org/schema/data/mongo/spring-mongo-1.7.xsd Http://www.springframework.org/schema/beans H Ttp://www.springframework.org/schema/beans/spring-beans.xsd "> <!--Redis Cache section--<bean id=" Poolconfig
        "class=" Redis.clients.jedis.JedisPoolConfig "> <property name=" maxidle "value=" ${redis.maxidle} "/> <property name= "Maxtotal" value= "${redis.mAxtotal} "/> <property name=" Maxwaitmillis "value=" ${redis.maxwaitmillis} "/> <property name=" Testonborrow "value=" ${redis.testonborrow} "/> </bean> <bean id=" Redisconnectionfactory "Clas s= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory" P:host-name= "${redis.host}" p:port= "$ {Redis.port} "p:password=" ${redis.pass} "p:pool-config-ref=" Poolconfig "/> <bean id=" RedisTemplate "CLA ss= "Org.springframework.data.redis.core.RedisTemplate" > <property name= "connectionfactory" ref= "Redisconnec Tionfactory "/> </bean> <!--loading Redis--<bean id=" Redisservice "class=" com.maigangle.b2b.com Mon.redis.RedisSpringServiceImpl "> <!--control redis Switch--<property name=" Isuse "value=" true ">& Lt;/property> </bean> </beans>

Redisspringserviceimpl.java

Package Com.maigangle.b2b.common.redis;
Import java.io.UnsupportedEncodingException;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.LinkedHashMap;
Import java.util.List;

Import Java.util.Map;
Import Org.apache.commons.lang.StringUtils;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.dao.DataAccessException;
Import org.springframework.data.redis.RedisConnectionFailureException;
Import org.springframework.data.redis.connection.RedisConnection;
Import Org.springframework.data.redis.core.RedisCallback;

Import Org.springframework.data.redis.core.RedisTemplate;
Import Com.alibaba.fastjson.JSON;

Import com.maigangle.b2b.common.exception.CommonException; /** * Redis Interface Implementation * * @author * @since * @version 1.0 * */public class Redisspringserviceimpl implements REDISSPR
    Ingservice {private static String Rediscode = "Utf-8"; Private Boolean isuse; Redis switch Private byte[] getBytes (String str) {try{return str.getbytes (Rediscode);
        } catch (Unsupportedencodingexception e) {return str.getbytes ();
    }} public Boolean Isuse () {return isuse;
    The public void Setisuse (Boolean isuse) {this.isuse = Isuse;

    } @Autowired Private redistemplate<string, string> redistemplate;
        public void Pub (string channel, string param) {if (!isuse) return;
    Redistemplate.convertandsend (channel, param); }/** * @param key */Public Long del (final String ... keys) {if (!isuse) return Nu
        ll try {Long re = Redistemplate.execute (new rediscallback<long> () {Public long Doinredis (
                    Redisconnection connection) throws DataAccessException {long result = 0;
     for (int i = 0; i < keys.length; i++) {result = Connection.del (Keys[i].getbytes ());                   result++;
                } return result;
            }
            });
        return re;
        } catch (Exception e) {return null; }}/** * @param key * @param value * @param livetime */public void Set (final byte[] Ke
        Y, Final byte[] value, final long Livetime) {if (!isuse) return; try {redistemplate.execute (new rediscallback<long> () {public Long Doinredis (Redisconne
                    Ction connection) throws DataAccessException {Connection.set (key, value);
                    if (Livetime > 0) {connection.expire (key, Livetime);
                } return 1L;
        }
            });
            } catch (Exception e) {Closeswitch (e);
        E.printstacktrace (); }}/** * @param key * @param value * @param lIvetime */public void Set (string key, String value, Long Livetime) {This.set (GetBytes (key), GetBytes (VA
    Lue), livetime);
        }/** * @param key * @param livetime */public boolean expire (String key, long Livetime) {
        if (!isuse) return false; try {return Redistemplate.execute (new rediscallback<boolean> () {public Boolean doinred Is (redisconnection connection) throws DataAccessException {return Connection.expire (Key.getbytes (), L
                Ivetime);
        }
            });
            } catch (Exception e) {Closeswitch (e);
            E.printstacktrace ();
        return false; }}/** * @param key * @param value */public void Set (string key, String value) {Thi
    S.set (key, value, 0L); }/** * @param key * @param value */public void set (byte[] key, byte[] value) {This.set ( KeY, value, 0L); }/** * @param key * @param value */public void Set (String key, byte[] value) {This.set (
    GetBytes (key), value, 0L); }/** * */@Override public void setojb (String key, Object value, long time) {This.set (ge
    Tbytes (Key), GetBytes (json.tojsonstring (value)), time);
            }/** * @param key * @return * * public string Get (final string key) {if (!isuse)
        return null; try {return Redistemplate.execute (new rediscallback<string> () {public String Doinredis  (Redisconnection connection) throws DataAccessException {try {byte[] bytes =
                        Connection.get (GetBytes (key));
                        if (bytes = = NULL | | bytes.length = = 0) {return null;
                    } return new String (bytes, rediscode); } catch (Unsupportedencodingexception e) {e.printstacktrace ();
                        } catch (Exception E1) {e1.printstacktrace ();
                    return null;
                } return "";
        }
            });
            } catch (Exception e) {Closeswitch (e);
            E.printstacktrace ();
        return null;
        }} public byte[] Get4byte (final String key) {if (!isuse) return null; try {return Redistemplate.execute (new rediscallback<byte[]> () {public byte[] Doinredis (Redisconnection connection) throws DataAccessException {try {return connect
                    Ion.get (GetBytes (key));
                        } catch (Exception E1) {e1.printstacktrace ();
                    return null;
        }
                }
            }); } catch (ExCeption e) {Closeswitch (e);
            E.printstacktrace ();
        return null;  }} @Override public <T> T getobj (string key, Class<t> ElementType) {string jsonstring =
        This.get (key);
        T obj;
        obj = Json.parseobject (jsonstring, ElementType); if (obj = = null) {try {obj = elementtype.newinstance ();//Prevent null pointer exception} catch (Insta ntiationexception |
            Illegalaccessexception e) {throw new Commonexception ("Get Redis Error:", e);
    }} return obj;
            }/** * @param pattern * @return */public void SetKeys (String pattern) {if (!isuse)
        Return
        try {Redistemplate.keys (pattern);
            } catch (Exception e) {Closeswitch (e);
        E.printstacktrace (); }}/** * @param key * @return * */public Boolean exists (final String Key) {if (!isuse) return false; try {return Redistemplate.execute (new rediscallback<boolean> () {public Boolean doinred
                Is (redisconnection connection) throws DataAccessException {return connection.exists (GetBytes (key));
        }
            });
            } catch (Exception e) {Closeswitch (e);
            E.printstacktrace ();
        return false;
    }}/** * @return * *//Public String flushdb () {//if (!isuse) return null; Return Redistemplate.execute (New rediscallback<string> () {//Public String Doinredis (redisconnection Connect
    ION) throws//DataAccessException {///CONNECTION.FLUSHDB ();
    return "OK";
    // }
    // });
        public Boolean flushdb () {if (!isuse) return false;
                try {return Redistemplate.execute (new rediscallback<boolean> () {Public Boolean Doinredis (redisconnection connection) throws DataAccessException {connection.flushdb ()
                    ;
                return true;
        }
            });
            } catch (Exception e) {Closeswitch (e);
            E.printstacktrace ();
        return false;
        }}/** * @return * * * public long dbsize () {if (!isuse) return 0; try {return Redistemplate.execute (new rediscallback<long> () {public Long Doinredis (Red
                Isconnection connection) throws DataAccessException {return connection.dbsize ();
        }
            });
            } catch (Exception e) {Closeswitch (e);
            E.printstacktrace ();
        return 0;
        }}/** * @return * */Public String ping () {if (!isuse) return null; try {return Redistemplate.execute (new Rediscallback<String> () {public String Doinredis (redisconnection connection) throws DataAccessException {
                return connection.ping ();
        }
            });
            } catch (Exception e) {Closeswitch (e);
            E.printstacktrace ();
        return null;
            }} private void Closeswitch (Exception e) {if (e instanceof redisconnectionfailureexception) {
        This.isuse = false; }}/** * Submit Check token * * @param token * @return */public Boolean Checktoke
        N (String token) {if (Stringutils.isblank (token)) {return false;
        } Object tk = This.get (token);
            if (tk! = null) {This.del (token);
        return true;
    } return false;
            } @Override public void Sethm (String key, map<string, string> Map, long Livetime) {if (!isuse)
        Return Final MAp<byte[], byte[]> hashes = new linkedhashmap<byte[], byte[]> (Map.size ()); For (map.entry<string, string> entry:map.entrySet ()) {Hashes.put (GetBytes ()), Entry.getkey (E
        Ntry.getvalue ())); } redistemplate.execute (New rediscallback<object> () {public Object Doinredis (redisconnection C
                onnection) {Connection.hmset (GetBytes (key), hashes);
                if (Livetime > 0) {connection.expire (GetBytes (key), livetime);
            } return null;
    }}, True);
        } @Override public map<string, string> gethm (String key) {final byte[] Rawkey = getBytes (key);
            Map<byte[], byte[]> entries = Redistemplate.execute (new rediscallback<map<byte[], byte[]>> () { Public map<byte[], byte[]> Doinredis (redisconnection connection) {return connection.hgetal
  L (Rawkey);          }}, True);
        map<string, string> map = new linkedhashmap<string, string> (Entries.size ()); For (map.entry<byte[], byte[]> entry:entries.entrySet ()) {try {map.put (new String) (En
            Try.getkey (), Rediscode), New String (Entry.getvalue (), Rediscode));
            } catch (Unsupportedencodingexception e) {return new hashmap<string, string> ();
    }} return map;
            } @Override public void setlist (String key, list<string> List, long Livetime) {if (!isuse)
        Return
        Final list<byte[]> listes = new Arraylist<byte[]> (List.size ());
        for (String value:list) {Listes.add (getBytes (value)); } redistemplate.execute (New rediscallback<object> () {
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.