HttpServletRequestWrapper模拟实现分布式Session
HttpSession的内容都放在一个单独的Map中,模拟远程分布式Session。
1.使用HttpServletRequestWrapper创建自定义Request
2.使用动态代理包装自定义Request返回的HttpSession对象
3.创建过滤器,使用自定义Request替换原有的Request对象。
4.在Servlet中得到的HttpSession对象,写入和读取内容都假设通过远程Session服务器。
创建自定义的Request,返回动态代理的HttpSession
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.concurrent.ConcurrentHashMap;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletRequestWrapper;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpServletResponseWrapper;
- import javax.servlet.http.HttpSession;
- public class RemoteSessionRequest extends HttpServletRequestWrapper {
- public RemoteSessionRequest(HttpServletRequest request) {
- super(request);
- }
- @Override
- public HttpSession getSession() {
- return RemoteSessionHandler.getInstance(super.getSession());
- }
- }
- class RemoteSessionHandler implements InvocationHandler {
- //模拟远程Session服务器,Key表示SessionId,Value表示该Session的内容
- private static Map<String, Map<String, Object>> map = new ConcurrentHashMap<String, Map<String, Object>>();
- private HttpSession session = null;
- private RemoteSessionHandler(HttpSession httpSession) {
- this.session = httpSession;
- };
- public static HttpSession getInstance(HttpSession httpSession) {
- InvocationHandler handler = new RemoteSessionHandler(httpSession);
- return (HttpSession) Proxy.newProxyInstance(httpSession.getClass().getClassLoader(), httpSession.getClass().getInterfaces(), handler);
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- if ("setAttribute".equals(method.getName())) {
- String id = session.getId();
- Map<String, Object> m = map.get(id);
- if (m == null) {
- m = new HashMap<String, Object>();
- map.put(id, m);
- }
- m.put((String) args[0], args[1]);
- System.out.println("[存入]key:" + args[0] + ",value:" + args[1]);
- return null;
- } else if ("getAttribute".equals(method.getName())) {
- String id = session.getId();
- Map<String, Object> m = map.get(id);
- if (m == null) {
- return null;
- }
- Object result = m.get(args[0]);
- System.out.println("[取出]key:" + args[0] + ",value:" + result);
- return result;
- }
- return method.invoke(session, args);
- }
- }
使用过滤器替换原有的Request
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.annotation.WebFilter;
- import javax.servlet.http.HttpServletRequest;
- @WebFilter("/*")
- public class SessionFilter implements Filter {
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- chain.doFilter(new RemoteSessionRequest((HttpServletRequest) request), response);
- }
- @Override
- public void destroy() {
- // TODO Auto-generated method stub
- }
- @Override
- public void init(FilterConfig arg0) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
在Servlet中按照原有方式使用HttpSession。
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- HttpSession session = request.getSession();
- session.setAttribute("name", "Hello");
- session.getAttribute("name");
- session.getAttribute("other");
- }
结果可以看到,他已经模拟从远程服务器存取数据
[存入]key:name,value:Hello
[取出]key:name,value:Hello
[取出]key:other,value:null
HttpServletRequestWrapper模拟实现分布式Session的更多相关文章
- SpringBoot 分布式session
SpringBoot 分布式session实现 1. 什么是分布式session 在集群环境中,不得不考虑的一个问题是用户访问产生的session如何处理.如过不做任何处理,用户将出现频繁俸禄的现象, ...
- springboot集成redis(mybatis、分布式session)
安装Redis请参考:<CentOS快速安装Redis> 一.springboot集成redis并实现DB与缓存同步 1.添加redis及数据库相关依赖(pom.xml) <depe ...
- Spring Session解决分布式Session问题的实现原理
使用Spring Session和Redis解决分布式Session跨域共享问题 上一篇介绍了如何使用spring Session和Redis解决分布式Session跨域共享问题,介绍了一个简单的案例 ...
- 分布式session的实现
一.分布式Session的几种实现方式 1.基于数据库的Session共享 2.基于NFS共享文件系统3.基于memcached 的session,如何保证 memcached 本身的高可用性?4. ...
- 可扩容分布式session方案
分布式session有以下几种方案: 1. 基于nfs(net filesystem)的session共享 将共享服务器目录mount各服务器的本地session目录,session读写受共享服务器i ...
- NoSQL-Redis【2】-实现分布式Session
经过一周紧张的开发和调试,终于把Redis实现的分布式Session发布到了生产环境.我在本地测试了100万的数据,Redis的速度确实让我满意,期待在线上有更好的表现. 一.配置windows-se ...
- [Node.js] Node + Redis 实现分布式Session方案
原文地址: http://www.moye.me/?p=565 Session是什么? Session 是面向连接的状态信息,是对 Http 无状态协议的补充. Session 怎么工作? Sessi ...
- 基于ZooKeeper的分布式Session实现(转)
1. 认识ZooKeeper ZooKeeper—— “动物园管理员”.动物园里当然有好多的动物,游客可以根据动物园提供的向导图到不同的场馆观赏各种类型的动物,而不是像走在原始丛林里,心惊胆颤的被 ...
- 微服务架构下分布式Session管理
转载本文需注明出处:EAII企业架构创新研究院(微信号:eaworld),违者必究.如需加入微信群参与微课堂.架构设计与讨论直播请直接回复此公众号:“加群 姓名 公司 职位 微信号”. 一.应用架构变 ...
随机推荐
- POJ——2251Dungeon Master(三维BFS)
Dungeon Master Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 25379 Accepted: 9856 D ...
- 【二分+扫描线乱搞】B. Producing Snow
注意二分写法... http://codeforces.com/problemset/problem/923/B #include<cstdio> #include<string.h ...
- R语言入门视频笔记--8--数据框
一.数据框 使用data.frame函数生成数据框 x <- c(20122014101:20122014128) y <- rnorm(28,85,18) #生成28个平均数为85,方差 ...
- LeetCode OJ--Valid Parentheses
http://oj.leetcode.com/problems/valid-parentheses/ 对栈的考察,看括号的使用方式是否合法. class Solution { public: bool ...
- android Activity生命周期的例子
package com.example.yanlei.yl2; import android.app.AlertDialog; import android.content.DialogInterfa ...
- 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 ...
- 递归获取JSON内容的key-value值
方法主体: 使用时,请在类中先声明一个Map,參数形式例如以下: JSONObject jobj = new JSONObject(JSONContent); 首次请传递jobj.
- UVA 1482 - Playing With Stones(SG打表规律)
UVA 1482 - Playing With Stones 题目链接 题意:给定n堆石头,每次选一堆取至少一个.不超过一半的石子,最后不能取的输,问是否先手必胜 思路:数值非常大.无法直接递推sg函 ...
- SolidEdge 如何由装配图快速生成爆炸视图
建立图纸精灵,组态中选择explode(没有下一步可选了) 点击完成即可绘制爆炸图
- socket 网络编程高速入门(一)教你编写基于UDP/TCP的服务(client)通信
由于UNIX和Win的socket大同小异,为了方便和大众化,这里先介绍Winsock编程. socket 网络编程的难点在入门的时候就是对基本函数的了解和使用,由于这些函数的结构往往比較复杂,參数大 ...