電商項目中,在單服務器時,用戶登陸時將用戶信息設置到 session
中,獲取用戶信息從 session
中獲取,退出時從 session
中刪除便可。java
但在搭建 Tomcat
集羣后,就須要考慮 Session
共享問題,可經過單點登陸解決方案實現,這裏主要有兩種方法,一種是經過 Redis + Cookie
本身實現,另外一種是藉助 Spring Session
框架解決。web
用戶登陸:redis
uuid
或 session.getId
生成惟一 id(token)
,設置到 cookie
中,將其寫給客戶端;user
對象)轉換爲 json
格式;key=token
,value=(user 的 json 格式)
,寫到 redis
中,並設置過時時間;退出登陸:spring
cookie
,從 cookie
中獲取到 token
;cookie
,將其過時時間設置爲 0
,再寫入到響應中,即刪除了 token
;redis
中刪除 token
;獲取用戶信息:json
cookie
中獲取到 token
;token
在 redis
中查詢相應的 user
對象的 json
串;json
串轉換爲 user
對象;因爲 token
和 user
對象都會存儲在 redis
中,因此這裏封裝一個 redis
的鏈接池和工具類。瀏覽器
首先,封裝一個 redis
鏈接池,每次直接從鏈接池中獲取 jedis
實例便可。服務器
public class RedisPool {
private static JedisPool jedisPool;
private static String redisIP = PropertiesUtil.getProperty("redis.ip", "192.168.23.130");
private static Integer redisPort = Integer.parseInt(PropertiesUtil.getProperty("redis.port", "6379"));
// 最大鏈接數
private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total", "20"));
// 最大的 idle 狀態的 jedis 實例個數
private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle", "10"));
// 最小的 idle 狀態的 jedis 實例個數
private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle", "2"));
// 在 borrow 一個 jedis 實例時,是否要進行驗證操做
private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow", "true"));
// 在 return 一個 jedis 實例時,是否要進行驗證操做
private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return", "true"));
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
jedisPool = new JedisPool(config, redisIP, redisPort, 1000*2);
}
public static Jedis getJedis() {
return jedisPool.getResource();
}
public static void returnJedis(Jedis jedis) {
jedis.close();
}
}
複製代碼
而後,再將其封裝成一個工具類,基本操做就是從 redis
鏈接池中獲取 jedis
實例,進行 set/get/expire
等操做,而後將其放回到 redis
鏈接池中。cookie
@Slf4j
public class RedisPoolUtil {
// exTime 以秒爲單位
public static Long expire(String key, int exTime) {
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.expire(key, exTime);
} catch (Exception e) {
log.error("expire key:{}, error", key, e);
}
RedisPool.returnJedis(jedis);
return result;
}
public static Long del(String key) {
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.del(key);
} catch (Exception e) {
log.error("del key:{}, error", key, e);
}
RedisPool.returnJedis(jedis);
return result;
}
public static String get(String key) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.get(key);
} catch (Exception e) {
log.error("get key:{}, error", key, e);
}
RedisPool.returnJedis(jedis);
return result;
}
public static String set(String key, String value) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.set(key, value);
} catch (Exception e) {
log.error("set key:{}, value:{}, error", key, value, e);
}
RedisPool.returnJedis(jedis);
return result;
}
// exTime 以秒爲單位
public static String setEx(String key, String value, int exTime) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.setex(key, exTime, value);
} catch (Exception e) {
log.error("setex key:{}, value:{}, error", key, value, e);
}
RedisPool.returnJedis(jedis);
return result;
}
}
複製代碼
將 user
對象存儲在 redis
中,須要轉換爲 json
格式,從 redis
中獲取 user
對象,又須要轉換爲 user
對象。這裏封裝一個 json
的工具類。session
JsonUtil
工具類主要使用 ObjectMapper
類。app
bean
類轉換爲 String
類型,使用 writerValueAsString
方法。String
類型轉換爲 bean
類,使用 readValue
方法。@Slf4j
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
// 序列化時將全部字段列入
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.ALWAYS);
// 取消默認將 DATES 轉換爲 TIMESTAMPS
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
// 忽略空 bean 轉 json 的錯誤
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
// 全部日期樣式統一
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 忽略 在 json 字符串中存在,在 java 對象中不存在對應屬性的狀況
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static <T> String obj2Str(T obj) {
if (obj == null) { return null; }
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to String error", e);
return null;
}
}
public static <T> String obj2StrPretty(T obj) {
if (obj == null) { return null; }
try {
return obj instanceof String ? (String) obj :
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to String error", e);
return null;
}
}
public static <T> T str2Obj(String str, Class<T> clazz) {
if (StringUtils.isEmpty(str) || clazz == null) {
return null;
}
try {
return clazz.equals(String.class) ? (T)str : objectMapper.readValue(str, clazz);
} catch (Exception e) {
log.warn("Parse String to Object error", e);
return null;
}
}
public static <T> T str2Obj(String str, TypeReference<T> typeReference) {
if (StringUtils.isEmpty(str) || typeReference == null) {
return null;
}
try {
return typeReference.getType().equals(String.class) ? (T)str : objectMapper.readValue(str, typeReference);
} catch (Exception e) {
log.warn("Parse String to Object error", e);
return null;
}
}
public static <T> T str2Obj(String str, Class<?> collectionClass, Class<?> elementClass) {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClass);
try {
return objectMapper.readValue(str, javaType);
} catch (Exception e) {
log.warn("Parse String to Object error", e);
return null;
}
}
}
複製代碼
登陸時須要將 token
設置到 cookie
中返回給客戶端,退出時須要從 request
中攜帶的 cookie
中讀取 token
,設置過時時間後,又將其設置到 cookie
中返回給客戶端,獲取用戶信息時,獲取用戶信息時,須要從 request
中攜帶的 cookie
中讀取 token
,在 redis
中查詢後得到 user
對象。這裏呢,也封裝一個 cookie
的工具類。
在 CookieUtil
中:
readLoginToken
方法主要從 request
讀取 Cookie
;writeLoginToken
方法主要設置 Cookie
對象加到 response
中;delLoginToken
方法主要從 request
中讀取 Cookie
,將其 maxAge
設置爲 0
,再添加到 response
中;@Slf4j
public class CookieUtil {
private static final String COOKIE_DOMAIN = ".happymmall.com";
private static final String COOKIE_NAME = "mmall_login_token";
public static String readLoginToken(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
log.info("read cookieName:{}, cookieValue:{}", cookie.getName(), cookie.getValue());
if (StringUtils.equals(COOKIE_NAME, cookie.getName())) {
log.info("return cookieName:{}, cookieValue:{}", cookie.getName(), cookie.getValue());
return cookie.getValue();
}
}
}
return null;
}
public static void writeLoginToken(HttpServletResponse response, String token) {
Cookie cookie = new Cookie(COOKIE_NAME, token);
cookie.setDomain(COOKIE_DOMAIN);
cookie.setPath("/");
// 防止腳本攻擊
cookie.setHttpOnly(true);
// 單位是秒,若是是 -1,表明永久;
// 若是 MaxAge 不設置,cookie 不會寫入硬盤,而是在內存,只在當前頁面有效
cookie.setMaxAge(60 * 60 * 24 * 365);
log.info("write cookieName:{}, cookieValue:{}", cookie.getName(), cookie.getValue());
response.addCookie(cookie);
}
public static void delLoginToken(HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (StringUtils.equals(COOKIE_NAME, cookie.getName())) {
cookie.setDomain(COOKIE_DOMAIN);
cookie.setPath("/");
// maxAge 設置爲 0,表示將其刪除
cookie.setMaxAge(0);
log.info("del cookieName:{}, cookieValue:{}", cookie.getName(), cookie.getValue());
response.addCookie(cookie);
return;
}
}
}
}
}
複製代碼
登陸時驗證密碼後:
CookieUtil.writeLoginToken(response, session.getId());
RedisShardedPoolUtil.setEx(session.getId(), JsonUtil.obj2Str(serverResponse.getData()), Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
複製代碼
退出登陸時:
String loginToken = CookieUtil.readLoginToken(request);
CookieUtil.delLoginToken(request, response);
RedisShardedPoolUtil.del(loginToken);
複製代碼
獲取用戶信息時:
String loginToken = CookieUtil.readLoginToken(request);
if (StringUtils.isEmpty(loginToken)) {
return ServerResponse.createByErrorMessage("用戶未登陸,沒法獲取當前用戶信息");
}
String userJsonStr = RedisShardedPoolUtil.get(loginToken);
User user = JsonUtil.str2Obj(userJsonStr, User.class);
複製代碼
另外,在用戶登陸後,每次操做後,都須要重置 Session
的有效期。可使用過濾器來實現。
public class SessionExpireFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException { }
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String loginToken = CookieUtil.readLoginToken(httpServletRequest);
if (StringUtils.isNotEmpty(loginToken)) {
String userJsonStr = RedisShardedPoolUtil.get(loginToken);
User user = JsonUtil.str2Obj(userJsonStr, User.class);
if (user != null) {
RedisShardedPoolUtil.expire(loginToken, Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() { }
}
複製代碼
還須要在 web.xml
文件中進行配置:
<filter>
<filter-name>sessionExpireFilter</filter-name>
<filter-class>com.mmall.controller.common.SessionExpireFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionExpireFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
複製代碼
redis + cookie
方式實現的單點登陸對代碼侵入性比較大;cookie
,而有些瀏覽器不支持 cookie
;Cookie
設置 domain
時必須統一,服務器也必須統一域名方式;Spring Session
是 Spring
的項目之一,它提供了建立和管理 Server
HTTPSession
的方案。並提供了集羣 Session
功能,默認採用外置的 Redis
來存儲 Session
數據,以此來解決 Session
共享的問題。
Spring Session
能夠無侵入式地解決 Session
共享問題,可是不能進行分片。
一、引入 Spring Session pom
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
複製代碼
二、配置 DelegatingFilterProxy
<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
複製代碼
三、配置 RedisHttpSessionConfiguration
<bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="1800" />
</bean>
複製代碼
四、配置 JedisPoolConfig
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="20" />
</bean>
複製代碼
五、配置 JedisSessionFactory
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<property name="hostName" value="192.168.23.130" />
<property name="port" value="6379" />
<property name="database" value="0" />
<property name="poolConfig" ref="jedisPoolConfig" />
</bean>
複製代碼
六、配置 DefaultCookieSerializer
<bean id="defaultCookieSerializer" class="org.springframework.session.web.http.DefaultCookieSerializer">
<property name="cookieName" value="SESSION_NAME" />
<property name="domainName" value=".happymmall.com" />
<property name="useHttpOnlyCookie" value="true" />
<property name="cookiePath" value="/" />
<property name="cookieMaxAge" value="31536000" />
</bean>
複製代碼
用戶登陸時:
session.setAttribute(Const.CURRENT_USER, response.getData());
複製代碼
退出登陸時:
session.removeAttribute(Const.CURRENT_USER);
複製代碼
得到用戶信息時:
User user = (User) session.getAttribute(Const.CURRENT_USER);
複製代碼