【问题标题】:Redis still returns null entries even when they are expiredRedis 仍然返回 null 条目,即使它们已过期
【发布时间】:2019-10-04 12:01:57
【问题描述】:

我正在使用带有 Redis 的 Spring Repositories 并希望将有关用户的数据存储 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 中。我担心这会用大量过期数据填充数据库。有没有办法删除过期的实体。

【问题讨论】:

  • 面临同样的问题!!是否有解决方法,因为我也收到了旧条目。到期时间 5 分钟 - 检索旧数据将使值变为空!!

标签: java spring spring-boot redis spring-data-redis


【解决方案1】:

当过期设置为正值时,执行相应的EXPIRE命令。除了保留原始副本外,还会在 Redis 中保留一个幻影副本,并设置为在原始副本后 5 分钟过期。

更多信息请参考here

希望this post能帮到你。

【讨论】:

  • 请考虑在答案本身中添加更多详细信息,并仅使用链接作为参考。
【解决方案2】:

简短的回答是:

添加以下注释:

@EnableRedisRepositories(enableKeyspaceEvents = EnableKeyspaceEvents.ON_STARTUP)

在你的主类(SpringBootApplication)之上

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

【讨论】:

    猜你喜欢
    • 2019-12-25
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    相关资源
    最近更新 更多