Reputation: 1158
I am using Spring Repositories with Redis and want to store data about user for 10 seconds and expire them (and delete them) from redis. I know expiring and deleting is different, but is there an easy way to delete them like I am expiring them automatically.
I have the following entity
@RedisHash(value = "User", timeToLive = 10)
public class User {
@Id
private String id;
@Indexed
@ApiModelProperty(notes = "First name of the user")
private String firstName;
@ApiModelProperty(notes = "Last name of the user")
private String lastName;
...
...
}
Repository
@Repository
public interface UserRepository extends CrudRepository<User, String> {
}
Configuration for Redis
@Configuration
public class RedisConfig {
@Value("${redis.hostname}")
private String redisHostname;
@Value("${redis.port}")
private int redisPort;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(redisHostname, redisPort);
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
When I get all the entities with findAll method from the repository if they are expired I get a bunch of null values, and I can see that they are in the redis with a redis client. I am worried that this will fill the db with a lot of expired data. Is there a way to delete the expired entities.
Upvotes: 1
Views: 5058
Reputation: 776
The short answer is:
Put the following annotation:
@EnableRedisRepositories(enableKeyspaceEvents = EnableKeyspaceEvents.ON_STARTUP)
Above your main class (SpringBootApplication)
Objects will now get removed from the redis store :)
Upvotes: 2
Reputation: 886
When the expiration is set to a positive value, the corresponding EXPIRE command is executed. In addition to persisting the original, a phantom copy is persisted in Redis and set to expire five minutes after the original one.
for more information, please reference here
Hope this post helps you.
Upvotes: 1