Jedis key expiry
The call to redisTemplate.expire(KEY, 30, TimeUnit.SECONDS)
takes place in your init method which will be called after dependency injection takes place to initialize your class. At this point, the key Session
doesn't exist, so invoking the expire command has no effect. See the Redis.io description for EXPIRE for a complete description. You could test this by capturing the return result from the expire command and log the results.
Instead of calling expire
in the init method, you should call it in the save method to set the expiration time on your session when it is saved.
Related videos on Youtube
Comments
-
Happy almost 2 years
I am trying to understand redis/jedis with spring. I am stuck somewhere where I can't able to expiry my key after certain period of time.
Can anyone please help ?
public class SessionCacheRepositoryImpl implements SessionCacheRepository { private static final String KEY = "Session"; private RedisTemplate<String, Object> redisTemplate; private HashOperations hashOperations; @Autowired public SessionCacheRepositoryImpl(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } @PostConstruct private void init() { hashOperations = redisTemplate.opsForHash(); redisTemplate.expire(KEY, 30, TimeUnit.SECONDS); } public void saveSession(final Session session) { hashOperations.put(KEY, session.getSessionID(), session); } }
And this is my config class
private RedisTemplate<String, Object> template; @Bean JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory jedisConFactory = new JedisConnectionFactory(); jedisConFactory.setHostName("localhost"); jedisConFactory.setPort(36919); return jedisConFactory; } @Bean public RedisTemplate<String, Object> redisTemplate() { template = new RedisTemplate<String, Object>(); template.setConnectionFactory(jedisConnectionFactory()); template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class)); return template; }
-
Tague Griffith almost 7 yearsI forgot to mention in your code sample you always use the key
Session
- so all your saves will overwrite the same key. Is that what you want? -
Happy almost 7 yearsNo, I was just doing poc with that actually I was thinking of saving key as session ID, but now in put I have to define sessionId two times. One for key and one for identifier.
hashOperations.put(session.getSessionID(), session.getSessionID(), session); redisTemplate.expire(session.getSessionID(), 30, TimeUnit.MINUTES);
is there any way that I can just use sessionID just as key and save my object?