• 分布式应用session会话管理基于redis


    转载自:http://blog.csdn.net/u010497606/article/details/52935556

    session会话在单台服务器下不会出现共享问题,现在应用部署方式都是分布式,或者集群部署,这样必然会面临一个问题,session共享


    session共享的解决方案也有很多,


    一、web服务器的粘性请求,比如采用nginx请求分发,使用ip_hash这种负载均衡方式,客户端请求只会被分发到相同的后台server,这样可以避免session共享的问题。但是缺点也很明显

    二、基于数据库存储(网站用户量大的情况下,频繁dml数据,对db压力大)

    三、基于cookie存储(安全问题、虽然可以加密存储、但是我觉得永远不能将敏感数据放在客户端,不信任啊O(∩_∩)O哈哈~)

    四、服务器内置的session复制域(比如was下提供session复制功能、但这个损耗服务器内存)

    五、基于nosql(memcache、redis都可以)






    http请求是无状态的


    这里要引入一个概念sessionidsession对象当客户端首次访问时,创建一个新的session对象.并同时生成一个sessionId,并在此次响应中将sessionId以响应报文的方式些回客户端浏览器内存或以重写url方式送回客户端,来保持整个会话

    也就是说客户端request请求时候,如果获取了session,就默认分配一个jessionid,然后通过response响应到客户端cookie,然后客户端下一次请求,默认会携带这个jessionid请求到服务端,服务端拿到这个jessionid来区分不同的客户端。


    说清楚这些,就可以从sessionid入手了,要实现将session信息存入redis,总结了下大概是三点:

    1.实现httpsession接口,重写我们需要用到的方法,比如set get这些。。balabala一堆......

    2.继承HttpServletRequestWrapper,这个类里面有getSession()方法,我们需要重写,来取自定义session

    3.实现filter,用来拦截客户端请求,获取我们自定义的request,从而获得session


    具体实现:

    1.实现httpsession接口

    [java] view plain copy
    1. public class HttpSessionWrapper implements HttpSession {  
    2.     protected final Logger logger = LoggerFactory.getLogger(getClass());  
    3.     private String sid = "";  
    4.     private HttpServletRequest request;  
    5.     private HttpServletResponse response;  
    6.     private final long creationTime = System.currentTimeMillis();  
    7.     private final long lastAccessedTime = System.currentTimeMillis();  
    8.     private SessionMeta meta;  
    9.     public HttpSessionWrapper() {  
    10.     }  
    11.     public HttpSessionWrapper(String sid,SessionMeta meta, HttpServletRequest request,  
    12.             HttpServletResponse response) {  
    13.         this.sid=sid;  
    14.         this.request=request;  
    15.         this.response=response;  
    16.         this.meta=meta;  
    17.     }  
    18.     public Object getAttribute(String name) {  
    19.         logger.info(getClass()+"getAttribute(),name:"+name);  
    20.         Jedis jedis =null;  
    21.         Object obj =null;  
    22.         String jsonStr = null;  
    23.         try {  
    24.             jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort());  
    25.             jsonStr = jedis.get(name);  
    26.             if(jsonStr!=null||StringUtils.isNotEmpty(jsonStr)){  
    27.                 jedis.expire(name, meta.getSeconds());// 重置过期时间  
    28.                 obj =JSON.parseObject(jsonStr, User.class); //反序列对象  
    29.             }  
    30.             if (jedis != null) {  
    31.                 JedisPoolStore.getInstance().returnJedis(jedis);  
    32.             }  
    33.             return obj;  
    34.         }   
    35.         catch (JSONException je) {  
    36.             logger.error(je.getMessage());  
    37.                 if (null != jedis)  
    38.                     JedisPoolStore.getInstance().returnJedis(jedis);  
    39.             return jsonStr;  
    40.         }  
    41.         catch (Exception e) {  
    42.             logger.error(e.getMessage());  
    43.             if (e instanceof JedisException) {  
    44.                 if (null != jedis)  
    45.                     JedisPoolStore.getInstance().returnBrokenJedis(jedis);  
    46.             } else {  
    47.                 if (null != jedis)  
    48.                     JedisPoolStore.getInstance().returnJedis(jedis);  
    49.             }  
    50.             throw new HttpSessionException(" session 异常  getAttribute() name:"+name);  
    51.         }  
    52.     }  
    53.     public void setAttribute(String name, Object value) {  
    54.         logger.info(getClass()+"setAttribute(),name:"+name);  
    55.         Jedis jedis =null;  
    56.         try {  
    57.             jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort());  
    58.             if(value instanceof String){  
    59.                 String value_ =(String) value;  
    60.                 jedis.set(name,value_);//普通字符串对象  
    61.             }else{  
    62.                 jedis.set(name, JSON.toJSONString(value));//序列化对象  
    63.             }  
    64.               
    65.             jedis.expire(name, meta.getSeconds());// 重置过期时间  
    66.             if (jedis != null) {  
    67.                 JedisPoolStore.getInstance().returnJedis(jedis);  
    68.             }  
    69.         } catch (Exception e) {  
    70.             logger.error(e.getMessage());  
    71.             if (e instanceof JedisException) {  
    72.                 if (null != jedis)  
    73.                     JedisPoolStore.getInstance().returnBrokenJedis(jedis);  
    74.             } else {  
    75.                 if (null != jedis)  
    76.                     JedisPoolStore.getInstance().returnJedis(jedis);  
    77.             }  
    78.             throw new HttpSessionException(" session 异常  setAttribute() name:"+name+",value:"+value);  
    79.         }  
    80.           
    81.     }  
    82.     /** 
    83.      * 不可用 
    84.      * @deprecated 
    85.      *  
    86.      */  
    87.     public void invalidate() {  
    88.         logger.info(getClass()+"invalidate()");  
    89.     }  
    90.   
    91.     public void removeAttribute(String name) {  
    92.         logger.info(getClass()+"removeAttribute(),name:"+name);  
    93.         if(StringUtils.isNotEmpty(name)){  
    94.             Jedis jedis =null;  
    95.             try {  
    96.                 jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort());  
    97.                 jedis.del(name);  
    98.                 if (jedis != null) {  
    99.                     JedisPoolStore.getInstance().returnJedis(jedis);  
    100.                 }  
    101.             } catch (Exception e) {  
    102.                 logger.error(e.getMessage());  
    103.                 if (e instanceof JedisException) {  
    104.                     if (null != jedis)  
    105.                         JedisPoolStore.getInstance().returnBrokenJedis(jedis);  
    106.                 } else {  
    107.                     if (null != jedis)  
    108.                         JedisPoolStore.getInstance().returnJedis(jedis);  
    109.                 }  
    110.                 throw new HttpSessionException(" session 异常  removeAttribute() name:"+name);  
    111.             }  
    112.         }  
    113.       
    114.     }  
    115.     /** 
    116.      * 不可用 
    117.      * @deprecated 
    118.      *  
    119.      */  
    120.     public Object getValue(String name) {  
    121.         return null;  
    122.     }  
    123.     /** 
    124.      * 不可用 
    125.      * @deprecated 
    126.      *  
    127.      */  
    128.     public Enumeration getAttributeNames() {  
    129.          return  null;  
    130.   
    131.     }              
    132.     /** 
    133.      * 不可用 
    134.      * @deprecated 
    135.      *  
    136.      */  
    137.     public String[] getValueNames() {  
    138.          return  null;      
    139.      }  
    140.     /** 
    141.      * 不可用 
    142.      * @deprecated 
    143.      *  
    144.      */  
    145.     public void putValue(String name, Object value) {  
    146.     }  
    147.     /** 
    148.      * 不可用 
    149.      * @deprecated 
    150.      *  
    151.      */  
    152.     public void removeValue(String name) {  
    153.     }  
    154.   
    155.     public long getCreationTime() {  
    156.         return  creationTime;  
    157.     }  
    158.   
    159.     public String getId() {  
    160.         logger.info(getClass()+"getId():"+sid);  
    161.         return sid;  
    162.     }  
    163.   
    164.     public long getLastAccessedTime() {  
    165.         return lastAccessedTime;  
    166.     }  
    167.     /** 
    168.      * 不可用 
    169.      * @deprecated 
    170.      *  
    171.      */  
    172.     public ServletContext getServletContext() {  
    173.         return null;  
    174.     }  
    175.     /** 
    176.      * 不可用 
    177.      * @deprecated 
    178.      *  
    179.      */  
    180.     public void setMaxInactiveInterval(int interval) {  
    181.     }  
    182.     /** 
    183.      * 不可用 
    184.      * @deprecated 
    185.      *  
    186.      */  
    187.     public int getMaxInactiveInterval() {  
    188.         return 0;  
    189.     }  
    190.     /** 
    191.      * 不可用 
    192.      * @deprecated 
    193.      *  
    194.      */  
    195.     public HttpSessionContext getSessionContext() {  
    196.         return null;  
    197.     }  
    198.     /** 
    199.      * 不可用 
    200.      * @deprecated 
    201.      *  
    202.      */  
    203.     public boolean isNew() {  
    204.         logger.info(getClass()+"isNew()");  
    205.         return false;  
    206.     }  
    207. }  

    2.继承HttpServletRequestWrapper

    [java] view plain copy
    1. /*** 
    2.  *  
    3.  * @author xiaoshuai 
    4.  * 
    5.  */  
    6. public class DefinedHttpServletRequestWrapper extends HttpServletRequestWrapper{  
    7.         protected final Logger logger = LoggerFactory.getLogger(getClass());  
    8.   
    9.         private HttpSessionWrapper currentSession;  
    10.         private HttpServletRequest request;  
    11.         private HttpServletResponse response;  
    12.         private String sid = "";  
    13.         private  SessionMeta meta;  
    14.            
    15.         public DefinedHttpServletRequestWrapper(HttpServletRequest request) {  
    16.             super(request);  
    17.         }  
    18.   
    19.         public DefinedHttpServletRequestWrapper(String sid, HttpServletRequest request) {  
    20.             super(request);  
    21.             this.sid = sid;  
    22.         }  
    23.   
    24.         public DefinedHttpServletRequestWrapper(String sid, SessionMeta meta,HttpServletRequest request,  
    25.                 HttpServletResponse response) {  
    26.             super(request);  
    27.             this.request = request;  
    28.             this.response = response;  
    29.             this.sid = sid;  
    30.             this.meta=meta;  
    31.         }  
    32.   
    33.         @Override  
    34.         public HttpSession getSession(boolean create) {  
    35.             if(currentSession != null) {  
    36.                    return currentSession;  
    37.                  }  
    38.              if(!create) {  
    39.                return null;  
    40.              }  
    41.              currentSession = new HttpSessionWrapper(sid,meta, request, response);  
    42.              return currentSession;  
    43.         }  
    44.   
    45.         @Override  
    46.         public HttpSession getSession() {  
    47.           return getSession(true);  
    48.         }  
    49.       
    50. }  

    3.实现filter

    [java] view plain copy
    1. public class SessionFilter implements Filter{  
    2.     protected final Logger logger = LoggerFactory.getLogger(getClass());  
    3.     private static SessionMeta meta = new SessionMeta();  
    4.     private static final String host ="host";  
    5.     private static final String port ="port";  
    6.     private static final String seconds="seconds";  
    7.       
    8.     public void init(FilterConfig filterConfig) throws ServletException {  
    9.         logger.debug("init filterConfig info");  
    10.         meta.setHost(filterConfig.getInitParameter(host));  
    11.         meta.setPort(Integer.parseInt(filterConfig.getInitParameter(port)));  
    12.         meta.setSeconds(Integer.parseInt(filterConfig.getInitParameter(seconds)));  
    13.     }  
    14.   
    15.     public void doFilter(ServletRequest request, ServletResponse response,  
    16.             FilterChain chain) throws IOException, ServletException {  
    17.          //从cookie中获取sessionId,如果此次请求没有sessionId,重写为这次请求设置一个sessionId  
    18.         HttpServletRequest httpRequest = (HttpServletRequest) request;  
    19.         HttpServletResponse httpResponse = (HttpServletResponse) response;  
    20.         String sid = CookieHelper.findCookieInfo(httpRequest,CookieHelper.COOKIE_DOMAIN_NAME);  
    21.         if(StringUtils.isEmpty(sid) ){  
    22.             try {  
    23.                 sid =CookieHelper.saveCookie(SessionId.doIds(), httpResponse);  
    24.             } catch (Exception e) {  
    25.                 e.printStackTrace();  
    26.             }  
    27.         }  
    28.         logger.info("JESSIONID:"+sid);  
    29.         chain.doFilter(new DefinedHttpServletRequestWrapper(sid,meta,httpRequest, httpResponse), response);  
    30.     }  
    31.   
    32.     public void destroy() {  
    33.     }  
    34.   
    35. }  


    3.配置web.xml

    [java] view plain copy
    1. <!-- session过滤器 -->  
    2. <filter>  
    3.     <filter-name>sessionFilter</filter-name>  
    4.     <filter-class>cn.session.filter.SessionFilter</filter-class>  
    5.     <init-param>  
    6.         <param-name>host</param-name>  
    7.         <param-value>10.1.193.1</param-value>  
    8.     </init-param>  
    9.     <init-param>  
    10.         <param-name>port</param-name>  
    11.         <param-value>6372</param-value>  
    12.     </init-param>  
    13.     <init-param>  
    14.         <param-name>seconds</param-name>  
    15.         <param-value>1800</param-value>  
    16.     </init-param>  
    17. </filter>  
    18. <filter-mapping>  
    19.     <filter-name>sessionFilter</filter-name>  
    20.     <url-pattern>/*</url-pattern>  
    21. </filter-mapping>  




    第一次产生sessionid访问:



    系统登录后存用户信息至redis,以及产生令牌:




    关于安全这块,因为不管登录系统与否,sessionid都会产生,这时候就会产生一个问题,因为cookie是可以被修改的,就会产生一个问题,撞session的分享。。。换成不同的sessionid去请求系统。。。总有一天会撞上。。


    SO,我这边是这样处理的,

    当登录成功之后,产生一个token令牌,产生规则的话自己定,一堆密钥比如系统名字+sessionid+userid+固定字符,产生一个加密的字符串,放入cookie。

    这样当我们获取当前登录用户时,解密token,获取sessionid,然后取redis用户信息。。(切记这里不要直接通过sessionid取用户信息,有风险!!!)

    用户没有登录成功,自然也没有这个令牌。。。


    这里又有另外一个问题,用户如果禁用cookie呢????? so what.....   下次再说这个。。。


    水平有限,如果你有更好的方式,请联系我,交流................................tks!!!!
    1. public class HttpSessionWrapper implements HttpSession { 
    2.     protected final Logger logger = LoggerFactory.getLogger(getClass()); 
    3.     private String sid = ""
    4.     private HttpServletRequest request; 
    5.     private HttpServletResponse response; 
    6.     private final long creationTime = System.currentTimeMillis(); 
    7.     private final long lastAccessedTime = System.currentTimeMillis(); 
    8.     private SessionMeta meta; 
    9.     public HttpSessionWrapper() { 
    10.     } 
    11.     public HttpSessionWrapper(String sid,SessionMeta meta, HttpServletRequest request, 
    12.             HttpServletResponse response) { 
    13.         this.sid=sid; 
    14.         this.request=request; 
    15.         this.response=response; 
    16.         this.meta=meta; 
    17.     } 
    18.     public Object getAttribute(String name) { 
    19.         logger.info(getClass()+"getAttribute(),name:"+name); 
    20.         Jedis jedis =null
    21.         Object obj =null
    22.         String jsonStr = null
    23.         try
    24.             jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort()); 
    25.             jsonStr = jedis.get(name); 
    26.             if(jsonStr!=null||StringUtils.isNotEmpty(jsonStr)){ 
    27.                 jedis.expire(name, meta.getSeconds());// 重置过期时间 
    28.                 obj =JSON.parseObject(jsonStr, User.class); //反序列对象 
    29.             } 
    30.             if (jedis != null) { 
    31.                 JedisPoolStore.getInstance().returnJedis(jedis); 
    32.             } 
    33.             return obj; 
    34.         }  
    35.         catch (JSONException je) { 
    36.             logger.error(je.getMessage()); 
    37.                 if (null != jedis) 
    38.                     JedisPoolStore.getInstance().returnJedis(jedis); 
    39.             return jsonStr; 
    40.         } 
    41.         catch (Exception e) { 
    42.             logger.error(e.getMessage()); 
    43.             if (e instanceof JedisException) { 
    44.                 if (null != jedis) 
    45.                     JedisPoolStore.getInstance().returnBrokenJedis(jedis); 
    46.             } else
    47.                 if (null != jedis) 
    48.                     JedisPoolStore.getInstance().returnJedis(jedis); 
    49.             } 
    50.             throw new HttpSessionException(" session 异常  getAttribute() name:"+name); 
    51.         } 
    52.     } 
    53.     public void setAttribute(String name, Object value) { 
    54.         logger.info(getClass()+"setAttribute(),name:"+name); 
    55.         Jedis jedis =null
    56.         try
    57.             jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort()); 
    58.             if(value instanceof String){ 
    59.                 String value_ =(String) value; 
    60.                 jedis.set(name,value_);//普通字符串对象 
    61.             }else
    62.                 jedis.set(name, JSON.toJSONString(value));//序列化对象 
    63.             } 
    64.              
    65.             jedis.expire(name, meta.getSeconds());// 重置过期时间 
    66.             if (jedis != null) { 
    67.                 JedisPoolStore.getInstance().returnJedis(jedis); 
    68.             } 
    69.         } catch (Exception e) { 
    70.             logger.error(e.getMessage()); 
    71.             if (e instanceof JedisException) { 
    72.                 if (null != jedis) 
    73.                     JedisPoolStore.getInstance().returnBrokenJedis(jedis); 
    74.             } else
    75.                 if (null != jedis) 
    76.                     JedisPoolStore.getInstance().returnJedis(jedis); 
    77.             } 
    78.             throw new HttpSessionException(" session 异常  setAttribute() name:"+name+",value:"+value); 
    79.         } 
    80.          
    81.     } 
    82.     /** 
    83.      * 不可用 
    84.      * @deprecated 
    85.      *  
    86.      */ 
    87.     public void invalidate() { 
    88.         logger.info(getClass()+"invalidate()"); 
    89.     } 
    90.  
    91.     public void removeAttribute(String name) { 
    92.         logger.info(getClass()+"removeAttribute(),name:"+name); 
    93.         if(StringUtils.isNotEmpty(name)){ 
    94.             Jedis jedis =null
    95.             try
    96.                 jedis =JedisPoolStore.getInstance().getJedis(meta.getHost(), meta.getPort()); 
    97.                 jedis.del(name); 
    98.                 if (jedis != null) { 
    99.                     JedisPoolStore.getInstance().returnJedis(jedis); 
    100.                 } 
    101.             } catch (Exception e) { 
    102.                 logger.error(e.getMessage()); 
    103.                 if (e instanceof JedisException) { 
    104.                     if (null != jedis) 
    105.                         JedisPoolStore.getInstance().returnBrokenJedis(jedis); 
    106.                 } else
    107.                     if (null != jedis) 
    108.                         JedisPoolStore.getInstance().returnJedis(jedis); 
    109.                 } 
    110.                 throw new HttpSessionException(" session 异常  removeAttribute() name:"+name); 
    111.             } 
    112.         } 
    113.      
    114.     } 
    115.     /** 
    116.      * 不可用 
    117.      * @deprecated 
    118.      *  
    119.      */ 
    120.     public Object getValue(String name) { 
    121.         return null
    122.     } 
    123.     /** 
    124.      * 不可用 
    125.      * @deprecated 
    126.      *  
    127.      */ 
    128.     public Enumeration getAttributeNames() { 
    129.          return  null
    130.  
    131.     }             
    132.     /** 
    133.      * 不可用 
    134.      * @deprecated 
    135.      *  
    136.      */ 
    137.     public String[] getValueNames() { 
    138.          return  null;     
    139.      } 
    140.     /** 
    141.      * 不可用 
    142.      * @deprecated 
    143.      *  
    144.      */ 
    145.     public void putValue(String name, Object value) { 
    146.     } 
    147.     /** 
    148.      * 不可用 
    149.      * @deprecated 
    150.      *  
    151.      */ 
    152.     public void removeValue(String name) { 
    153.     } 
    154.  
    155.     public long getCreationTime() { 
    156.         return  creationTime; 
    157.     } 
    158.  
    159.     public String getId() { 
    160.         logger.info(getClass()+"getId():"+sid); 
    161.         return sid; 
    162.     } 
    163.  
    164.     public long getLastAccessedTime() { 
    165.         return lastAccessedTime; 
    166.     } 
    167.     /** 
    168.      * 不可用 
    169.      * @deprecated 
    170.      *  
    171.      */ 
    172.     public ServletContext getServletContext() { 
    173.         return null
    174.     } 
    175.     /** 
    176.      * 不可用 
    177.      * @deprecated 
    178.      *  
    179.      */ 
    180.     public void setMaxInactiveInterval(int interval) { 
    181.     } 
    182.     /** 
    183.      * 不可用 
    184.      * @deprecated 
    185.      *  
    186.      */ 
    187.     public int getMaxInactiveInterval() { 
    188.         return 0
    189.     } 
    190.     /** 
    191.      * 不可用 
    192.      * @deprecated 
    193.      *  
    194.      */ 
    195.     public HttpSessionContext getSessionContext() { 
    196.         return null
    197.     } 
    198.     /** 
    199.      * 不可用 
    200.      * @deprecated 
    201.      *  
    202.      */ 
    203.     public boolean isNew() { 
    204.         logger.info(getClass()+"isNew()"); 
    205.         return false
    206.     } 

    2.继承HttpServletRequestWrapper

    [java] view plain copy
    1. /*** 
    2. *  
    3. * @author xiaoshuai 
    4. * 
    5. */ 
    6. public class DefinedHttpServletRequestWrapper extends HttpServletRequestWrapper{ 
    7.         protected final Logger logger = LoggerFactory.getLogger(getClass()); 
    8.  
    9.         private HttpSessionWrapper currentSession; 
    10.         private HttpServletRequest request; 
    11.         private HttpServletResponse response; 
    12.         private String sid = ""
    13.         private  SessionMeta meta; 
    14.           
    15.         public DefinedHttpServletRequestWrapper(HttpServletRequest request) { 
    16.             super(request); 
    17.         } 
    18.  
    19.         public DefinedHttpServletRequestWrapper(String sid, HttpServletRequest request) { 
    20.             super(request); 
    21.             this.sid = sid; 
    22.         } 
    23.  
    24.         public DefinedHttpServletRequestWrapper(String sid, SessionMeta meta,HttpServletRequest request, 
    25.                 HttpServletResponse response) { 
    26.             super(request); 
    27.             this.request = request; 
    28.             this.response = response; 
    29.             this.sid = sid; 
    30.             this.meta=meta; 
    31.         } 
    32.  
    33.         @Override 
    34.         public HttpSession getSession(boolean create) { 
    35.             if(currentSession != null) { 
    36.                    return currentSession; 
    37.                  } 
    38.              if(!create) { 
    39.                return null
    40.              } 
    41.              currentSession = new HttpSessionWrapper(sid,meta, request, response); 
    42.              return currentSession; 
    43.         } 
    44.  
    45.         @Override 
    46.         public HttpSession getSession() { 
    47.           return getSession(true); 
    48.         } 
    49.      

    3.实现filter

    [java] view plain copy
    1. public class SessionFilter implements Filter{ 
    2.     protected final Logger logger = LoggerFactory.getLogger(getClass()); 
    3.     private static SessionMeta meta = new SessionMeta(); 
    4.     private static final String host ="host"
    5.     private static final String port ="port"
    6.     private static final String seconds="seconds"
    7.      
    8.     public void init(FilterConfig filterConfig) throws ServletException { 
    9.         logger.debug("init filterConfig info"); 
    10.         meta.setHost(filterConfig.getInitParameter(host)); 
    11.         meta.setPort(Integer.parseInt(filterConfig.getInitParameter(port))); 
    12.         meta.setSeconds(Integer.parseInt(filterConfig.getInitParameter(seconds))); 
    13.     } 
    14.  
    15.     public void doFilter(ServletRequest request, ServletResponse response, 
    16.             FilterChain chain) throws IOException, ServletException { 
    17.          //从cookie中获取sessionId,如果此次请求没有sessionId,重写为这次请求设置一个sessionId 
    18.         HttpServletRequest httpRequest = (HttpServletRequest) request; 
    19.         HttpServletResponse httpResponse = (HttpServletResponse) response; 
    20.         String sid = CookieHelper.findCookieInfo(httpRequest,CookieHelper.COOKIE_DOMAIN_NAME); 
    21.         if(StringUtils.isEmpty(sid) ){ 
    22.             try
    23.                 sid =CookieHelper.saveCookie(SessionId.doIds(), httpResponse); 
    24.             } catch (Exception e) { 
    25.                 e.printStackTrace(); 
    26.             } 
    27.         } 
    28.         logger.info("JESSIONID:"+sid); 
    29.         chain.doFilter(new DefinedHttpServletRequestWrapper(sid,meta,httpRequest, httpResponse), response); 
    30.     } 
    31.  
    32.     public void destroy() { 
    33.     } 
    34.  


    3.配置web.xml

    [java] view plain copy
    1. <!-- session过滤器 --> 
    2. <filter> 
    3.     <filter-name>sessionFilter</filter-name> 
    4.     <filter-class>cn.session.filter.SessionFilter</filter-class
    5.     <init-param> 
    6.         <param-name>host</param-name> 
    7.         <param-value>10.1.193.1</param-value> 
    8.     </init-param> 
    9.     <init-param> 
    10.         <param-name>port</param-name> 
    11.         <param-value>6372</param-value> 
    12.     </init-param> 
    13.     <init-param> 
    14.         <param-name>seconds</param-name> 
    15.         <param-value>1800</param-value> 
    16.     </init-param> 
    17. </filter> 
    18. <filter-mapping> 
    19.     <filter-name>sessionFilter</filter-name> 
    20.     <url-pattern>/*</url-pattern> 
    21. </filter-mapping> 




    第一次产生sessionid访问:



    系统登录后存用户信息至redis,以及产生令牌:




    关于安全这块,因为不管登录系统与否,sessionid都会产生,这时候就会产生一个问题,因为cookie是可以被修改的,就会产生一个问题,撞session的分享。。。换成不同的sessionid去请求系统。。。总有一天会撞上。。


    SO,我这边是这样处理的,

    当登录成功之后,产生一个token令牌,产生规则的话自己定,一堆密钥比如系统名字+sessionid+userid+固定字符,产生一个加密的字符串,放入cookie。

    这样当我们获取当前登录用户时,解密token,获取sessionid,然后取redis用户信息。。(切记这里不要直接通过sessionid取用户信息,有风险!!!)

    用户没有登录成功,自然也没有这个令牌。。。


    这里又有另外一个问题,用户如果禁用cookie呢????? so what.....   下次再说这个。。。


    水平有限,如果你有更好的方式,请联系我,交流................................tks!!!!
  • 相关阅读:
    mysql进阶语句优化---day40
    pymysql基本语法,sql注入攻击,python操作pymysql,数据库导入导出及恢复数据---day38
    单表查询,多表查询,子查询---day37
    mysql-数据类型,类型约束,联合唯一约束,表与表之间的关系,存储引擎---day36
    mysql安装及增删改查操作---day35
    死锁,互斥锁,递归锁,线程事件Event,线程队列Queue,进程池和线程池,回调函数,协程的使用,协程的例子---day33
    进程之间共享数据Manager,线程相关使用Thread,用类定义线程,守护线程setDaemon,线程锁Lock,线程信号量Semaphore---day32
    Docker部署go-fastdfs
    Docker部署gitlab
    Docker部署hasura
  • 原文地址:https://www.cnblogs.com/cxrz/p/8529537.html
Copyright © 2020-2023  润新知