【问题标题】:Implement maxIdle timout session using Redis使用 Redis 实现最大空闲超时会话
【发布时间】:2022-10-04 21:18:37
【问题描述】:

像带有 Redis 持久性的 Spring Session 一样,如何使用 Redis 作为缓存来实现最大空闲超时?我需要同时拥有全局超时和最大非活动超时。全局超时可以使用 Redis 中的EXPIRE 命令来实现,但是对于最大非活动时间,如何实现带有 Redis 的 Spring Session 以及使用 Redis 实现最大非活动时间的任何最佳解决方案?

【问题讨论】:

    标签: java spring caching redis spring-session


    【解决方案1】:

    像这样实现您的缓存,在此您必须跟踪何时使用此密钥。

    public class SmartCache {
        private RedisTemplate<String, Object> template;
        private String lastUsedTracker = "__inactive-duration::";
    
        public SmartCache(RedisTemplate<String, Object> template) {
            this.template = template;
        }
    
        private String lastUsedKey(String key) {
            return lastUsedTracker + key;
        }
    
        public void put(String key, Object val, long maxRetentionTime, long maxInactiveDuration) {
            template.opsForValue().set(key, val, maxRetentionTime, TimeUnit.MILLISECONDS);
            template.opsForValue().set(lastUsedKey(key), maxInactiveDuration, maxInactiveDuration, TimeUnit.MILLISECONDS);
        }
    
        public Object get(String key) {
            // ttl has expired
            Object val = template.opsForValue().get(key);
            if (val == null) {
                return null;
            }
    
            // if key was inactive then nothing to be done
            Object inactiveDuration = template.opsForValue().get(lastUsedKey(key));
            if (inactiveDuration == null) {
                return null;
            }
            
            // reset ttl of inactive key as its used
            Long ttl = (Long) inactiveDuration;
            template.opsForValue().set(lastUsedKey(key), ttl, ttl, TimeUnit.MILLISECONDS);
            return val;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 2013-06-18
      • 2021-12-28
      • 2012-02-17
      • 2022-01-25
      • 2014-04-24
      相关资源
      最近更新 更多