本文章主要目的是配置session共享,为了巩固基础,捎带介绍了一些基础知识(网上搜索后觉得最全面的特引过来,节省时间),基础扎实的可以自动忽略。

基础篇:

1.了解java web中的session与cookie。

2.如何封装request和session这两个web项目中最常用的对象(以解决乱码为例)

进阶篇:

3.利用memcache实现session共享

在开发过程中,为了缓解访问压力,往往需要配置负载均衡,也就是相同的项目放在多台机子上,保证一台机子挂了,网站仍然可以正常访问,除了需要使用相同的数据源,资料源之外,最大的问题莫过于session的共享了。这里session共享的核心在于改变原来session中的键值对存放在每台机子各自的内存中的情况,而是把session中的内容集中存放在一个nosql数据库中。

3.1封装request对象:

package com.sse.roadshow.session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.sse.roadshow.common.SpyMemcachedManager; public class HttpServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {
String sid = "";
private SpyMemcachedManager spyMemcachedManager; public HttpServletRequestWrapper(String sid, HttpServletRequest request,SpyMemcachedManager spyMemcachedManager) {
super(request);
this.sid = sid;
this.spyMemcachedManager = spyMemcachedManager;
} public HttpSession getSession(boolean create) {
return new HttpSessionSidWrapper(this.sid, super.getSession(create), this.spyMemcachedManager);
} public HttpSession getSession() {
return new HttpSessionSidWrapper(this.sid, super.getSession(), this.spyMemcachedManager);
}
}

通过封装传递数据源,并且覆盖getSession方法,自定义的session对象在下一步

3.2封装session对象

package com.sse.roadshow.session;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import com.sse.roadshow.common.Constants;
import com.sse.roadshow.common.SpyMemcachedManager;
import com.sse.roadshow.vo.Enumerator; public class HttpSessionSidWrapper extends HttpSessionWrapper { private String sid = "";
private Map map = new HashMap();
private SpyMemcachedManager spyMemcachedManager; @SuppressWarnings("rawtypes")
public HttpSessionSidWrapper(String sid, HttpSession session, SpyMemcachedManager spyMemcachedManager) {
super(session); if (spyMemcachedManager == null) {
System.out.println("spyMemcachedManager is null.....");
return;
}
this.spyMemcachedManager = spyMemcachedManager;
this.sid = sid;
Map memSession = null;
memSession = (Map) this.spyMemcachedManager.get(sid);
//sid没有加入到session中,需要初始化session,替换为自定义session
if (memSession == null) {
// System.out.println("memSession is null");
memSession = new HashMap();
// this.spyMemcachedManager.set(sid, memSession, Constants.SPMEM_EXPTIME);
if (session != null) {
Enumeration<String> names = session.getAttributeNames();
while (names.hasMoreElements()) {
String key = (String) names.nextElement();
memSession.put(key, session.getAttribute(key));
}
}
}
this.map = memSession;
} public Object getAttribute(String key) {
if (this.map != null && this.map.containsKey(key)) {
return this.map.get(key);
} else {
return null;
}
} @SuppressWarnings({ "unchecked", "rawtypes" })
public Enumeration getAttributeNames() {
return (new Enumerator(this.map.keySet(), true));
// return super.getAttributeNames();
} public void invalidate() {
// super.invalidate();
this.map.clear();
long s1= System.currentTimeMillis();
try {
spyMemcachedManager.delete(sid);
System.out.print("removeSession sid is:" + sid);
}
finally{
System.out.println(System.currentTimeMillis() -s1);
}
} public void removeAttribute(String name) {
// super.removeAttribute(name);
this.map.remove(name);
attributeChange();
// System.out.print("removeAttribute");
// System.out.println("key : " + name);
} @SuppressWarnings("unchecked")
public void setAttribute(String name, Object value) {
// super.setAttribute(name, value);
this.map.put(name, value);
attributeChange();
// System.out.print("setAttribute-");
// System.out.println("key : " + name + ", value : " + value);
} private void attributeChange() {
spyMemcachedManager.set(sid, this.map, Constants.MYFILTER_COOKIE_EXPTIME);
}
}

3.3引入我们刚才封装好的request对象:

使用过滤器过滤对应路径的请求,引入自定义request:

3.3.1自定义过滤器:

package com.sse.roadshow.filter;

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.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.sse.roadshow.common.Constants;
import com.sse.roadshow.common.SpyMemcachedManager;
import com.sse.roadshow.common.Util;
import com.sse.roadshow.session.HttpServletRequestWrapper; public class MemcachedSessionFilter extends HttpServlet implements Filter { private static final long serialVersionUID = 8928219999641126613L;
// private FilterConfig filterConfig;
private String cookieDomain = "";
private String cookiePath = "/";
private SpyMemcachedManager spyMemcachedManager; public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
String sessionId = "XmlBeanDefinitionReaderSid";
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
Cookie cookies[] = request.getCookies();
Cookie sCookie = null;
String sid = "";
if (cookies != null && cookies.length > 0) {
for (int i = 0; i < cookies.length; i++) {
sCookie = cookies[i];
if (sCookie.getName().equals(sessionId)) {
sid = sCookie.getValue();
}
}
} if (sid == null || sid.length() == 0) {
sid = java.util.UUID.randomUUID().toString();
Cookie mycookies = new Cookie(sessionId, sid);
mycookies.setMaxAge(-1);
mycookies.setPath("/");
mycookies.setHttpOnly(true);
mycookies.setDomain(Constants.DOMAIN);
response.addCookie(mycookies);
}
spyMemcachedManager = getBean(request); filterChain.doFilter(new HttpServletRequestWrapper(sid, request, spyMemcachedManager),
servletResponse);
} private SpyMemcachedManager getBean(HttpServletRequest request) {
if(Util.isNull(spyMemcachedManager)) {
spyMemcachedManager = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext()).getBean(SpyMemcachedManager.class);
}
return spyMemcachedManager;
} public void init(FilterConfig filterConfig) throws ServletException {
// this.filterConfig = filterConfig;
// this.sessionId = filterConfig.getInitParameter("sessionId");
this.cookiePath = filterConfig.getInitParameter("cookiePath");
if (this.cookiePath == null || this.cookiePath.length() == 0) {
this.cookiePath = "/";
} this.cookieDomain = filterConfig.getInitParameter("cookieDomain");
if (this.cookieDomain == null) {
this.cookieDomain = Constants.DOMAIN;
}
} public SpyMemcachedManager getSpyMemcachedManager() {
return spyMemcachedManager;
} public void setSpyMemcachedManager(SpyMemcachedManager spyMemcachedManager) {
this.spyMemcachedManager = spyMemcachedManager;
}
}

3.3.2.在web.xml中配置filter:

<!-- session共享过滤器 -->
<filter>
<filter-name>mySessionFilter</filter-name>
<filter-class>com.sse.roadshow.filter.MemcachedSessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>mySessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

这样session共享就配置完毕了。

http://blog.csdn.net/shandalue/article/details/41522043

java项目使用memcache实现session共享+session基础的更多相关文章

  1. 如何实现session共享

    http://www.cnblogs.com/xiehuiqi220/p/3592300.html 首先我们应该明白,为什么要实现共享,如果你的网站是存放在一个机器上,那么是不存在这个问题的,因为会话 ...

  2. 【原创】搭建Nginx(负载均衡)+Redis(Session共享)+Tomcat集群

    为什么移除首页?哪里不符合要求?倒是回我邮件啊! 一.环境搭建 Linux下Vagrant搭建Tomcat7.Java7 二.Nginx的安装配置与测试 *虚拟机下转至root sudo -i 1)下 ...

  3. 搭建Nginx(负载均衡)+Redis(Session共享)+Tomcat集群

    一.环境搭建 Linux下Vagrant搭建Tomcat7.Java7 二.Nginx的安装配置与测试 *虚拟机下转至root sudo -i 1)下载并解压(目前官网最新版本) 创建安装目录:mkd ...

  4. linux memcached Session共享

    memcached memcached是高性能的分布式缓存服务器用来集中缓存数据库查询结果,减少数据库访问次数提高动态web应用的响应速度 传统web架构的问题许多web应用都将数据保存在RDBMS中 ...

  5. session以及分布式服务器session共享

    一.session的本质 http协议是无状态的,即你连续访问某个网页100次和访问1次对服务器来说是没有区别对待的,因为它记不住你. 那么,在一些场合,确实需要服务器记住当前用户怎么办?比如用户登录 ...

  6. SSO解决session共享的几种方案

    之前做项目遇到了这个sso系统,当时只是理解了一部分,今天偶尔发现一篇文章,觉得写的不错,增加了sso知识: 单点登录在现在的系统架构中广泛存在,他将多个子系统的认证体系打通,实现了一个入口多处使用, ...

  7. nginx+iis+redis+Task.MainForm构建分布式架构 之 (redis存储分布式共享的session及共享session运作流程)

    本次要分享的是利用windows+nginx+iis+redis+Task.MainForm组建分布式架构,上一篇分享文章制作是在windows上使用的nginx,一般正式发布的时候是在linux来配 ...

  8. Memcache+Tomcat9集群实现session共享(非jar式配置, 手动编写Memcache客户端)

    Windows上两个tomcat, 虚拟机中ip为192.168.0.30的centos上一个(测试用三台就够了, 为了测试看见端口所以没有使用nginx转发请求) 开始 1.windows上开启两个 ...

  9. Nginx+Tomcat+Memcache实现负载均衡及Session共享

    第一部分 环境介绍 部署环境: Host1:Nginx.Memcached.Tomcat1 Host2:Tomcat2 Tomcat_version:8.0.38 第二部分 Nginx+Tomcat实 ...

随机推荐

  1. Illustrated C#学习笔记(一)

    迄今为止最容易看懂的一本C#入门图书,的确是,很不错的一本书,继续读下去,并做好相关笔记吧. Chapter 1 C#和.NET框架 主要讲述了一些.NET框架下的一些不明觉厉的名词如CLR,CLI. ...

  2. 初探JS-html5移动端发送指定内容短信到指定号码

    原理:利用a标签跳转指定网址: sms://[号码]?body=[内容] //安卓 sms://[号码]&body=[内容] //IOS 首先简单的做两个input,一个用于输入内容,一个用于 ...

  3. pl sql练习(2)

    1.尽可能了解oracle的功能,因为很多业务逻辑oracle已经为我们做了,比如oracle已经预定义了大量的异常代码,我们不必要写自己的异常而增加代码的复杂度. 例如oracle定义了当找不到符合 ...

  4. UIView和其子类的几个初始化函数执行的时机

    -(id)initWithFrame:(CGRect)frame - UIView的指定初始化方法; 总是发送给UIView去初始化, 除非是从一个nib文件中加载的; -(id)initWithCo ...

  5. final的深入理解 - final数据

    先通过例子看一看: package com.sotaof.testfinal; public class Value { int i; public Value(int i){ this.i = i; ...

  6. 使用jquery插件uploadify上传文件的方法与疑问

    我是学生一枚,专业也不是计算机,但又要用到很多相关技术,所以在技术基础不牢靠的情况下,硬着头皮在做.最近在做一个小项目需要上传图片,而且是需要用ajax的方式.但是利用jquery的ajax方法总会有 ...

  7. yii操作数据库(AR)

    模型: 有多少数据表,就建立多少模型 模型其实就是类 我们对数据库进行操作,需要实例化模型类,产生对象 通过对象调用相关的方法,就可以实现数据库的操作   增加记录 [php] $post =newP ...

  8. Ubuntu系统下创建python数据挖掘虚拟环境

    虚拟环境:   虚拟环境是用于创建独立的python环境,允许我们使用不同的python模块和版本,而不混淆.   让我们了解一下产品研发过程中虚拟环境的必要性,在python项目中,显然经常要使用不 ...

  9. 【Python备忘】python判断文件和文件夹是否存在

    python判断文件和文件夹是否存在 import os os.path.isfile('test.txt') #如果不存在就返回False os.path.exists(directory) #如果 ...

  10. 寒冰王座(hd1248)

    寒冰王座 Problem Description 不死族的巫妖王发工资拉,死亡骑士拿到一张N元的钞票(记住,只有一张钞票),为了防止自己在战斗中频繁的死掉,他决定给自己买一些道具,于是他来到了地精商店 ...