我正在使用CrudRepository
连接到我的Spring Boot应用程序中的Redis,并使用实体中的一个带有@TimeToLive
的带注释字段来过期:
@RedisHash("keyspace")
public class MyRedisEntity {
@Id String key;
MyPojo pojo;
@TimeToLive Long ttl;
}
public interface MyRedisRepository extends CrudRepository<MyRedisEntity, String>{}
现在,当到期时,myRedisRepo.findAll()
为到期的实体返回null。我发现redis(或spring-data redis)将所有插入的实体的id存储在一个以键空间为键的集合中:
redis-cli> smembers keyspace
0) key0
1) key1
2) key2
...
redis-cli> hgetall key0
(empty list or set)
我怀疑此集合用于findAll
调用,由于过期而不再作为哈希映射出现的ID返回null。另外,我尝试使用RedisKeyExpiredEvent
的侦听器,并使用onApplicationEvent
中存储库的delete方法,但这无济于事。
@Component
public class RedisExpirationListener implements ApplicationListener<RedisKeyExpiredEvent> {
private MyRedisRepository myRedisRepository;
@Autowired
public RedisExpirationListener(MyRedisRepository myRedisRepository) {
this.myRedisRepository = myRedisRepository;
}
@Override
public void onApplicationEvent(RedisKeyExpiredEvent redisKeyExpiredEvent) {
if (redisKeyExpiredEvent.getKeyspace().equals("keyspace")) {
myRedisRepository.deleteById(new String(redisKeyExpiredEvent.getId()));
}
}
}
我应该怎么做才能只获得非null条目?理想情况下,我希望将过期条目完全从redis中删除,因此不要出现在findAll
中,但是如果存储库方法可以返回非null值列表就足够了。
(是的,我知道幻像行为,但我认为这与我想要的东西无关)