【问题标题】:RedisTemplate expire doesn't workRedisTemplate 过期不起作用
【发布时间】:2015-05-25 06:35:05
【问题描述】:

我正在尝试在 RedisTemplate 中测试 expire 方法。例如,我将会话存储在 redis 中,然后尝试检索会话并检查值是否相同。对于过期会话,我使用 redisTemplate 的 expire() 方法,而对于过期会话,我使用 getExpire() 方法。但它不起作用。如何测试存储在 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));    
    }    
}

但测试失败并出现 AssertionError:

预期:16 实际:0

更新: 我以为 getExpire() 方法不起作用,但实际上 expire() 方法不起作用。它返回假。 redisTemplate 是一个自动装配到测试类的 Spring Bean。 TestCache 类中还有许多其他测试方法可以正常工作。

【问题讨论】:

  • 密钥是否存在,要过期吗?您的代码不包含创建密钥的部分。如果可以应用过期,expire 返回 true。有关详细信息,请参阅redis.io/commands/pexpire
  • session,我作为参数发送给redisTemplate.expire() 是一个键String session = "SESSION_123";
  • 我的意思是,在您的 redis 实例上进行测试时是否存在密钥“SESSION_123”。
  • 它必须存在。在我的代码中,我使用该密钥使会话到期。我在课前启动redis服务器,课后停止。
  • 不知道为什么,redisTemplate从expire()方法返回false

标签: java unit-testing session redis


【解决方案1】:

我设置了以下代码来对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 数据都会消失。

您还应该向expireSession (assertTrue(cache.expireSession(session, duration));) 添加一个断言,以确保到期有效。

【讨论】:

  • 为什么需要调用 flushAll ?我有一些代码在每次 Tomcat 重新启动时清除 Redis 缓存。我发现代码中有一个flushAll返回RedisTemplate
  • 这只是为了让测试用例创建一个干净的状态。
猜你喜欢
  • 1970-01-01
  • 2016-11-24
  • 2020-11-04
  • 2020-09-20
  • 2011-07-17
  • 2012-05-23
  • 1970-01-01
  • 2015-06-19
相关资源
最近更新 更多