HttpSession的内容都放在一个单独的Map中,模拟远程分布式Session。

1.使用HttpServletRequestWrapper创建自定义Request
2.使用动态代理包装自定义Request返回的HttpSession对象
3.创建过滤器,使用自定义Request替换原有的Request对象。
4.在Servlet中得到的HttpSession对象,写入和读取内容都假设通过远程Session服务器。

创建自定义的Request,返回动态代理的HttpSession

  1. import java.lang.reflect.InvocationHandler;
  2. import java.lang.reflect.Method;
  3. import java.lang.reflect.Proxy;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. import java.util.concurrent.ConcurrentHashMap;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletRequestWrapper;
  9. import javax.servlet.http.HttpServletResponse;
  10. import javax.servlet.http.HttpServletResponseWrapper;
  11. import javax.servlet.http.HttpSession;
  12. public class RemoteSessionRequest extends HttpServletRequestWrapper {
  13. public RemoteSessionRequest(HttpServletRequest request) {
  14. super(request);
  15. }
  16. @Override
  17. public HttpSession getSession() {
  18. return RemoteSessionHandler.getInstance(super.getSession());
  19. }
  20. }
  21. class RemoteSessionHandler implements InvocationHandler {
  22. //模拟远程Session服务器,Key表示SessionId,Value表示该Session的内容
  23. private static Map<String, Map<String, Object>> map = new ConcurrentHashMap<String, Map<String, Object>>();
  24. private HttpSession session = null;
  25. private RemoteSessionHandler(HttpSession httpSession) {
  26. this.session = httpSession;
  27. };
  28. public static HttpSession getInstance(HttpSession httpSession) {
  29. InvocationHandler handler = new RemoteSessionHandler(httpSession);
  30. return (HttpSession) Proxy.newProxyInstance(httpSession.getClass().getClassLoader(), httpSession.getClass().getInterfaces(), handler);
  31. }
  32. @Override
  33. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  34. if ("setAttribute".equals(method.getName())) {
  35. String id = session.getId();
  36. Map<String, Object> m = map.get(id);
  37. if (m == null) {
  38. m = new HashMap<String, Object>();
  39. map.put(id, m);
  40. }
  41. m.put((String) args[0], args[1]);
  42. System.out.println("[存入]key:" + args[0] + ",value:" + args[1]);
  43. return null;
  44. } else if ("getAttribute".equals(method.getName())) {
  45. String id = session.getId();
  46. Map<String, Object> m = map.get(id);
  47. if (m == null) {
  48. return null;
  49. }
  50. Object result = m.get(args[0]);
  51. System.out.println("[取出]key:" + args[0] + ",value:" + result);
  52. return result;
  53. }
  54. return method.invoke(session, args);
  55. }
  56. }

使用过滤器替换原有的Request

  1. import java.io.IOException;
  2. import javax.servlet.Filter;
  3. import javax.servlet.FilterChain;
  4. import javax.servlet.FilterConfig;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.ServletRequest;
  7. import javax.servlet.ServletResponse;
  8. import javax.servlet.annotation.WebFilter;
  9. import javax.servlet.http.HttpServletRequest;
  10. @WebFilter("/*")
  11. public class SessionFilter implements Filter {
  12. @Override
  13. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  14. chain.doFilter(new RemoteSessionRequest((HttpServletRequest) request), response);
  15. }
  16. @Override
  17. public void destroy() {
  18. // TODO Auto-generated method stub
  19. }
  20. @Override
  21. public void init(FilterConfig arg0) throws ServletException {
  22. // TODO Auto-generated method stub
  23. }
  24. }


在Servlet中按照原有方式使用HttpSession。

  1. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  2. HttpSession session = request.getSession();
  3. session.setAttribute("name", "Hello");
  4. session.getAttribute("name");
  5. session.getAttribute("other");
  6. }

结果可以看到,他已经模拟从远程服务器存取数据

[存入]key:name,value:Hello
[取出]key:name,value:Hello
[取出]key:other,value:null

HttpServletRequestWrapper模拟实现分布式Session的更多相关文章

  1. SpringBoot 分布式session

    SpringBoot 分布式session实现 1. 什么是分布式session 在集群环境中,不得不考虑的一个问题是用户访问产生的session如何处理.如过不做任何处理,用户将出现频繁俸禄的现象, ...

  2. springboot集成redis(mybatis、分布式session)

    安装Redis请参考:<CentOS快速安装Redis> 一.springboot集成redis并实现DB与缓存同步 1.添加redis及数据库相关依赖(pom.xml) <depe ...

  3. Spring Session解决分布式Session问题的实现原理

    使用Spring Session和Redis解决分布式Session跨域共享问题 上一篇介绍了如何使用spring Session和Redis解决分布式Session跨域共享问题,介绍了一个简单的案例 ...

  4. 分布式session的实现

    一.分布式Session的几种实现方式 1.基于数据库的Session共享 2.基于NFS共享文件系统3.基于memcached 的session,如何保证 memcached 本身的高可用性?4. ...

  5. 可扩容分布式session方案

    分布式session有以下几种方案: 1. 基于nfs(net filesystem)的session共享 将共享服务器目录mount各服务器的本地session目录,session读写受共享服务器i ...

  6. NoSQL-Redis【2】-实现分布式Session

    经过一周紧张的开发和调试,终于把Redis实现的分布式Session发布到了生产环境.我在本地测试了100万的数据,Redis的速度确实让我满意,期待在线上有更好的表现. 一.配置windows-se ...

  7. [Node.js] Node + Redis 实现分布式Session方案

    原文地址: http://www.moye.me/?p=565 Session是什么? Session 是面向连接的状态信息,是对 Http 无状态协议的补充. Session 怎么工作? Sessi ...

  8. 基于ZooKeeper的分布式Session实现(转)

    1.   认识ZooKeeper ZooKeeper—— “动物园管理员”.动物园里当然有好多的动物,游客可以根据动物园提供的向导图到不同的场馆观赏各种类型的动物,而不是像走在原始丛林里,心惊胆颤的被 ...

  9. 微服务架构下分布式Session管理

    转载本文需注明出处:EAII企业架构创新研究院(微信号:eaworld),违者必究.如需加入微信群参与微课堂.架构设计与讨论直播请直接回复此公众号:“加群 姓名 公司 职位 微信号”. 一.应用架构变 ...

随机推荐

  1. POJ——2251Dungeon Master(三维BFS)

    Dungeon Master Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 25379   Accepted: 9856 D ...

  2. 【二分+扫描线乱搞】B. Producing Snow

    注意二分写法... http://codeforces.com/problemset/problem/923/B #include<cstdio> #include<string.h ...

  3. R语言入门视频笔记--8--数据框

    一.数据框 使用data.frame函数生成数据框 x <- c(20122014101:20122014128) y <- rnorm(28,85,18) #生成28个平均数为85,方差 ...

  4. LeetCode OJ--Valid Parentheses

    http://oj.leetcode.com/problems/valid-parentheses/ 对栈的考察,看括号的使用方式是否合法. class Solution { public: bool ...

  5. android Activity生命周期的例子

    package com.example.yanlei.yl2; import android.app.AlertDialog; import android.content.DialogInterfa ...

  6. Centos 6.x 安装Python 3.4.3

    [root@squid ~]# sed -i 's#keepcache=0#keepcache=1#g' /etc/yum.conf [root@squid ~]# grep keepcache /e ...

  7. 递归获取JSON内容的key-value值

    方法主体: 使用时,请在类中先声明一个Map,參数形式例如以下: JSONObject jobj = new JSONObject(JSONContent); 首次请传递jobj.

  8. UVA 1482 - Playing With Stones(SG打表规律)

    UVA 1482 - Playing With Stones 题目链接 题意:给定n堆石头,每次选一堆取至少一个.不超过一半的石子,最后不能取的输,问是否先手必胜 思路:数值非常大.无法直接递推sg函 ...

  9. SolidEdge 如何由装配图快速生成爆炸视图

    建立图纸精灵,组态中选择explode(没有下一步可选了)   点击完成即可绘制爆炸图

  10. socket 网络编程高速入门(一)教你编写基于UDP/TCP的服务(client)通信

    由于UNIX和Win的socket大同小异,为了方便和大众化,这里先介绍Winsock编程. socket 网络编程的难点在入门的时候就是对基本函数的了解和使用,由于这些函数的结构往往比較复杂,參数大 ...