Files
spring-boot-demo/redis/src/test/java/com/ankurm/redis/HashTtlEventsOffTest.java
T

72 lines
2.4 KiB
Java

package com.ankurm.redis;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import java.time.Duration;
import java.util.List;
import com.ankurm.redis.hash.Session;
import com.ankurm.redis.hash.SessionRepository;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @RedisHash(timeToLive) with Boot's defaults: keyspace events are OFF, so Redis expires the hash
* and Spring Data Redis never hears about it. Writes docs/output/09-hash-ttl-events-off.txt.
*/
@RedisTest
class HashTtlEventsOffTest {
@Autowired
SessionRepository sessions;
@BeforeAll
static void serverDefaults() {
LocalRedis.reset();
}
@BeforeEach
void clean() {
LocalRedis.flush();
}
@Test
void theHashExpiresButTheIndexEntriesStay() {
try (Transcript t = new Transcript("09-hash-ttl-events-off.txt",
"@RedisHash(timeToLive = 2) with Boot's defaults (keyspace events OFF)")) {
t.section("Server setting");
t.cli("--no-raw", "CONFIG", "GET", "notify-keyspace-events");
t.section("Save a session that lives for two seconds");
sessions.save(new Session("s1", "ankur"));
t.line("sessions.save(new Session(\"s1\", \"ankur\"))");
t.cliSorted("KEYS", "*");
List<String> ttl = t.cli("--no-raw", "TTL", "session:s1");
assertThat(ttl.get(0)).isEqualTo("(integer) 2");
t.section("Wait for Redis to expire it");
await().atMost(Duration.ofSeconds(10)).until(() -> stringCount("session:s1") == 0);
t.cli("--no-raw", "EXISTS", "session:s1");
t.section("What is left behind");
t.cliSorted("KEYS", "*");
t.cliSorted("SMEMBERS", "session");
t.cliSorted("SMEMBERS", "session:user:ankur");
t.section("What the repository says");
t.line("sessions.findById(\"s1\") = %s", sessions.findById("s1"));
t.line("sessions.count() = %d", sessions.count());
assertThat(sessions.findById("s1")).isEmpty();
}
}
private long stringCount(String key) {
return Long.parseLong(Transcript.run(java.util.List.of("redis-cli", "-p", String.valueOf(LocalRedis.PORT), "EXISTS", key)).get(0));
}
}