![](/img/trans.png)
[英]redisTemplate @Resource doesn't work wit Spring Framework
[英]RedisTemplate expire doesn't work
我正在嘗試測試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()方法不起作用。 返回false。 redisTemplate是一個自動連接到測試類的spring Bean。 TestCache類中還有許多其他測試方法可以正常工作。
我設置了以下代碼來對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
( expireSession
( assertTrue(cache.expireSession(session, duration));
)中添加一個斷言,以確保到期有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.