ShiroRedisSessionDAO.kt 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package com.gxzc.zen.umps.config
  2. import com.gxzc.zen.common.config.cache.redis.RedisKeyGenerator
  3. import org.apache.shiro.session.Session
  4. import org.apache.shiro.session.mgt.eis.AbstractSessionDAO
  5. import org.slf4j.LoggerFactory
  6. import org.springframework.data.redis.core.RedisTemplate
  7. import java.io.Serializable
  8. import java.nio.charset.Charset
  9. import java.util.concurrent.TimeUnit
  10. /**
  11. * Shiro SessionDAO
  12. * 若继承自 AbstractSessionDAO 则不会将Session缓存(shiro-activeSessioCache:xxx)
  13. * 继承自 EnterpriseCacheSessionDAO 或 CachingSessionDAO 则自动将session缓存
  14. * 由于本项目使用Redis作为缓存框架,所以不需要额外缓存开销
  15. * @author NorthLan
  16. * @date 2018/4/24
  17. * @url https://noahlan.com
  18. */
  19. class ShiroRedisSessionDAO : AbstractSessionDAO {
  20. companion object {
  21. private val logger = LoggerFactory.getLogger(ShiroRedisSessionDAO::class.java)
  22. }
  23. private val properties: ShiroRedisProperties
  24. private val redisTemplate: RedisTemplate<String, Any>
  25. private var charset: Charset = Charsets.UTF_8
  26. constructor(redisTemplate: RedisTemplate<String, Any>, properties: ShiroRedisProperties, charset: Charset = Charsets.UTF_8) : super() {
  27. this.redisTemplate = redisTemplate
  28. this.properties = properties
  29. this.charset = charset
  30. }
  31. private fun getKey(originalKey: String): String {
  32. return "${properties.sessionPrefix}${RedisKeyGenerator.SEPARATOR}$originalKey"
  33. }
  34. override fun update(session: Session) {
  35. logger.debug("Update Session: ${session.id}")
  36. redisTemplate.opsForValue().set(getKey(session.id.toString()), session, properties.sessionTime, TimeUnit.SECONDS)
  37. }
  38. override fun getActiveSessions(): MutableCollection<Session> {
  39. logger.debug("Get Active Sessions")
  40. return mutableListOf()
  41. }
  42. override fun doReadSession(sessionId: Serializable): Session? {
  43. logger.debug("Read Session: $sessionId")
  44. return redisTemplate.opsForValue().get(getKey(sessionId.toString())) as? Session
  45. }
  46. /**
  47. * 创建 session
  48. */
  49. override fun doCreate(session: Session): Serializable {
  50. val sid = this.generateSessionId(session)
  51. this.assignSessionId(session, sid)
  52. logger.debug("Create Session: $sid")
  53. redisTemplate.opsForValue().set(getKey(sid.toString()), session, properties.sessionTime, TimeUnit.SECONDS)
  54. return sid
  55. }
  56. override fun delete(session: Session) {
  57. logger.debug("Delete Session: ${session.id}")
  58. redisTemplate.delete(getKey(session.id.toString()))
  59. }
  60. }