package com.gxzc.zen.umps.config import com.gxzc.zen.common.config.cache.redis.RedisKeyGenerator import org.apache.shiro.session.Session import org.apache.shiro.session.mgt.eis.AbstractSessionDAO import org.slf4j.LoggerFactory import org.springframework.data.redis.core.RedisTemplate import java.io.Serializable import java.nio.charset.Charset import java.util.concurrent.TimeUnit /** * Shiro SessionDAO * 若继承自 AbstractSessionDAO 则不会将Session缓存(shiro-activeSessioCache:xxx) * 继承自 EnterpriseCacheSessionDAO 或 CachingSessionDAO 则自动将session缓存 * 由于本项目使用Redis作为缓存框架,所以不需要额外缓存开销 * @author NorthLan * @date 2018/4/24 * @url https://noahlan.com */ class ShiroRedisSessionDAO : AbstractSessionDAO { companion object { private val logger = LoggerFactory.getLogger(ShiroRedisSessionDAO::class.java) } private val properties: ShiroRedisProperties private val redisTemplate: RedisTemplate private var charset: Charset = Charsets.UTF_8 constructor(redisTemplate: RedisTemplate, properties: ShiroRedisProperties, charset: Charset = Charsets.UTF_8) : super() { this.redisTemplate = redisTemplate this.properties = properties this.charset = charset } private fun getKey(originalKey: String): String { return "${properties.sessionPrefix}${RedisKeyGenerator.SEPARATOR}$originalKey" } override fun update(session: Session) { logger.debug("Update Session: ${session.id}") redisTemplate.opsForValue().set(getKey(session.id.toString()), session, properties.sessionTime, TimeUnit.SECONDS) } override fun getActiveSessions(): MutableCollection { logger.debug("Get Active Sessions") return mutableListOf() } override fun doReadSession(sessionId: Serializable): Session? { logger.debug("Read Session: $sessionId") return redisTemplate.opsForValue().get(getKey(sessionId.toString())) as? Session } /** * 创建 session */ override fun doCreate(session: Session): Serializable { val sid = this.generateSessionId(session) this.assignSessionId(session, sid) logger.debug("Create Session: $sid") redisTemplate.opsForValue().set(getKey(sid.toString()), session, properties.sessionTime, TimeUnit.SECONDS) return sid } override fun delete(session: Session) { logger.debug("Delete Session: ${session.id}") redisTemplate.delete(getKey(session.id.toString())) } }