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;
}
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.