Redis 仍然 returns 空条目,即使它们已过期

Redis still returns null entries even when they are expired

我正在将 Spring 存储库与 Redis 一起使用,并希望将有关用户的数据存储 10 秒并从 Redis 中过期(并删除它们)。 我知道过期和删除是不同的,但是有没有一种简单的方法可以像我自动过期一样删除它们。

我有以下实体

@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
public interface UserRepository extends CrudRepository<User, String> {
}

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

当我使用 findAll 方法从存储库中获取所有实体(如果它们已过期)时,我会得到一堆空值,并且我可以看到它们在带有 redis 客户端的 redis 中。我担心这会用大量过期数据填充数据库。有没有办法删除过期的实体。

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.

更多信息请参考here

希望对你有帮助。

简短的回答是:

添加以下注释:

@EnableRedisRepositories(enableKeyspaceEvents = EnableKeyspaceEvents.ON_STARTUP)

在你的主要class(SpringBootApplication)

之上

现在将从 redis 存储中删除对象:)