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 1339 poker card game (数组排序+辅助队列的方法,预处理O(nlogn),构造霍夫曼树O(n))

    poj.org/problem?id=1339 #include<iostream> #include<cstdio> #include<string> #incl ...

  2. Java中NIO、BIO、AIO相关概念及应用场景

    1.同步阻塞IO(JAVA BIO):同步并阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时,服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,当然可以通 ...

  3. mysql/oracle 连接参数中文变问号

    jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf8&useSSL=true

  4. spring boot -- 无法读取html文件,碰到的坑

    碰到的坑,无法Controller读取html文件 1. Controller类一定要使用@Controller注解,不要用@RestController 2. resource目录下创建templa ...

  5. 最短路中部分点只能从中任意选取K个问题

    题意:给N个点,还有另外m个点(其中只能选K个),求最短路. 思路:在SPFA的基础上,用一个数组来统计,在某点入队时(要拓展其他点了),若该点是m个点中的,则count[i]=原来的+1:若不是,则 ...

  6. LeetCode OJ--Evaluate Reverse Polish Notation

    http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ 栈使用 #include <iostream> #inc ...

  7. LeetCode OJ--Partition List

    http://oj.leetcode.com/problems/partition-list/ 链表的处理 #include <iostream> using namespace std; ...

  8. HTML 中 SELECT 选项分组

    <select name="viewType"> <option value selected>选择排序/显示方式</option> <o ...

  9. CentOS6、CentOS7配置Base源和epel源

    1.用yum安装软件报错 Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=6&arch=x86_64&a ...

  10. Codevs1062路由选择

    /* #include<iostream> #include<cstdio> #include<cstring> #define MAXN 301 using na ...