Redis 仍然返回 null 条目,即使它们已过期

我将 Spring Repositories 与 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 中。我担心这会用大量过期数据填充数据库。有没有办法删除过期的实体。


aluckdog
浏览 146回答 2
2回答

牧羊人nacy

简短的回答是:放置以下注释:@EnableRedisRepositories(enableKeyspaceEvents&nbsp;=&nbsp;EnableKeyspaceEvents.ON_STARTUP)在你的主类(SpringBootApplication)之上对象现在将从 redis 存储中删除:)

翻翻过去那场雪

当过期设置为正值时,执行相应的 EXPIRE 命令。除了保留原始副本外,还会在 Redis 中保留一个幻影副本,并设置为在原始副本后五分钟过期。欲了解更多信息,请参考此处希望这篇文章对你有所帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java