分布式部署SESSION同步缓存同步部署
概要
在分布式部署的情况下:
需要解决以下的问题
1.SESSION同步
在分布式部署的情况下,一般有多台服务器,如果某台服务器宕机,那么负载均衡会访问其他的应用服务器,如果session不同步,那么会显示该用户为未登录。
2.缓存同步的问题。
在单台服务器部署的情况,缓存就直接存储在进程内的缓存中,如果多台应用服务器的情况,如果某台机器更新了缓存,其他的机器都需要更新缓存。
JSAAS 解决方案
在JSAAS 中如果是单台服务器部署,平台使用ehcache 作为进程内缓存。如果在分布式的情况下,JSAAS 使用J2CHACHE实现。
J2CACHE 使用了两级缓存:
1.进程内缓存。
2.分布式缓存(REDIS)
好处在于,当读取缓存时可以使用进程内缓存,当缓存更新时,可以更新所有机器的进程内缓存。同时发布缓存到 分布式缓存。
其他机器读取缓存时,如果读取不到进程缓存,就从分布式缓存读取。
JSAAS 配置
1.缓存配置
编辑 spring-base.xml
修改如下:
<!--<bean id="iCache" class="com.redxun.core.cache.EhCache"> <property name="cacheName" value="tokenCache"></property> </bean>--><bean id="iCache" class="com.redxun.core.cache.J2CacheImpl" init-method="init" destroy-method="destroy"></bean> |
改成使用 J2CACHE
修改 j2cache.properties
这里有redis 可以有三种部署方式。
1.单redis 实例
redis.mode = singleredis.hosts =192.168.31.100:6379 |
2.一主二从三哨兵模式
redis.mode = sentinelredis.hosts =192.168.31.100:16001,192.168.31.100:16002,192.168.31.100:16003 |
配置哨兵的地址。
3.集群模式
redis.mode = clusterredis.hosts =192.168.31.100:8000,192.168.31.100:8001,192.168.31.100:8002,,192.168.31.100:8003,192.168.31.100:8004,192.168.31.100:8005 |
2.SESSION同步配置
编辑web.xml
<filter> <filter-name>j2cache-session-filter</filter-name> <filter-class>com.redxun.saweb.filter.J2CacheSessionFilter</filter-class> <init-param> <param-name>session.maxSizeInMemory</param-name> <param-value>2000</param-value> </init-param> <init-param> <param-name>session.maxAge</param-name> <param-value>1800</param-value> </init-param> <init-param> <param-name>cookie.name</param-name> <param-value>J2CACHE_SESSION_ID</param-value> </init-param> <init-param> <param-name>cookie.path</param-name> <param-value>/</param-value> </init-param> <init-param> <param-name>cookie.domain</param-name> <param-value></param-value> </init-param> </filter><filter-mapping> <filter-name>j2cache-session-filter</filter-name> <url-pattern>*</url-pattern> </filter-mapping> |
需要让上面的过滤器生效,这样session 就实现了不同应用服务器的同步。
3.测试SESSION同步
编辑文件测试代码如下:
demo.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html ><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body><%String name=request.getParameter("name");if(name==null){ out.println(session.getAttribute("name"));}else{ session.setAttribute("name",name);}%>A</body></html> |
这个文件准备两份,一个为A,一个为B。
服务器部署
部署两台TOMCAT ,部署一个nginx
NIGINX 配置如下:
http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream linuxidc { server localhost:8080; server localhost:8081; } server { listen 80; server_name localhost; location / { proxy_pass http://linuxidc; proxy_redirect default; } |
nginx 配置为80 ,后端为两台tomcat。
输入路径:
http://localhost/aps/demo.jsp?name=自由港
测试效果如下:


发现session 实现了同步。

浙公网安备 33010602011771号