问题描述
我正在尝试在 RedisTemplate 中测试 expire 方法.例如,我将 session 存储在 redis 中,然后尝试检索 session 并检查值是否相同.对于过期会话,我使用 redisTemplate 的 expire() 方法,对于获取过期会话,我使用 getExpire() 方法.但它不起作用.如何测试存储在 redis 中的值?
I'm trying to test expire method in RedisTemplate. For example, I store session in redis, and than try to retrieve session and check that values are the same. For expire session I use expire() method of redisTemplate and for getting expired session I use getExpire() method. But it doesn't work. How can I test value, that stored in redis?
//without import and fields
public class Cache() {
private StringRedisTemplate redisTemplate;
public boolean expireSession(String session, int duration) {
return redisTemplate.expire(session, duration, TimeUnit.MINUTES);
}
}
//Test class without imports and fields
public class TestCache() {
private Cache cache = new Cache();
@Test
public void testExpireSession() {
Integer duration = 16;
String session = "SESSION_123";
cache.expireSession(session, duration);
assertEquals(redisTemplate.getExpire(session, TimeUnit.MINUTES), Long.valueOf(duration));
}
}
但测试因断言错误而失败:
but test fails with AssertionError:
预期:16 实际:0
更新:我想,那个 getExpire() 方法不起作用,但实际上 expire() 方法不起作用.它返回假.redisTemplate 是一个自动装配到测试类的 spring Bean.TestCache 类中还有许多其他测试方法可以正常工作.
UPDATE:I thought, that getExpire() method doesn't work, but in fact expire() method doesn't work. It returns false. redisTemplate is a spring Bean that autowired to test class. There are many other test methods in TestCache class that work correctly.
推荐答案
我设置了以下代码来对 getExpire()
(jedis 2.5.2, spring-data-redis 1.4.2.发布):
I set up following code to perform a test on getExpire()
(jedis 2.5.2, spring-data-redis 1.4.2.RELEASE):
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
public class DemoApplicationTests {
@Autowired
private RedisTemplate<String, String> template;
@Test
public void contextLoads() {
template.getConnectionFactory().getConnection().flushAll();
assertFalse(template.hasKey("key"));
assertFalse(template.expire("key", 10, TimeUnit.MINUTES));
assertEquals(0, template.getExpire("key", TimeUnit.MINUTES).longValue());
template.opsForHash().put("key", "hashkey", "hashvalue");
assertTrue(template.hasKey("key"));
assertTrue(template.expire("key", 10, TimeUnit.MINUTES));
assertTrue(template.getExpire("key", TimeUnit.MINUTES) > 8);
}
}
根据您的 Redis 配置,如果您重新启动 Redis 实例,所有 Redis 数据都会消失.
Depending on your Redis configuration, all Redis data is gone if you restart your Redis instance.
您还应该向 expireSession
(assertTrue(cache.expireSession(session, duration));
) 添加断言以确保到期有效.
You should also add an assertion to expireSession
(assertTrue(cache.expireSession(session, duration));
) to make sure, the expiry worked.
这篇关于RedisTemplate 过期不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!