package com.goafanti.core.shiro.listener;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.core.shiro.cache.ShiroRedisCache;

public class CustomSessionListener implements SessionListener {

	private RedisTemplate<String, Object>	redisTemplate;

	private static final Logger				logger	= LoggerFactory.getLogger(CustomSessionListener.class);

	/**
	 * 一个回话的生命周期开始
	 */
	@Override
	public void onStart(Session session) {

	}

	/**
	 * 一个回话的生命周期结束
	 */
	@Override
	public void onStop(Session session) {
		removeFromCache(session);
	}

	@Override
	public void onExpiration(Session session) {
		removeFromCache(session);
	}

	private void removeFromCache(Session session) {
		Object sessionId = session.getId();
		if (sessionId != null && sessionId instanceof String) {
			sessionId = (String) sessionId;
			redisTemplate.delete(ShiroRedisCache.PREFIX + sessionId);
			LoggerUtils.debug(logger, "删除过期session，id:[%s]", sessionId);
		}
	}

	public RedisTemplate<String, Object> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

}
