赞
踩
利用redis的Expire命令,可以设置一个时间,以秒为单位,过期后,key值无效。此方法常用于登录验证码有效期的控制和其他需要设置有效期的数据控制。
命令及例子:
命令:expire key seconds(设置key的有效时间)、ttl key(查询key剩余的有效时间)
例子:set yzcode “876590”(设置yzcode的值为“876590”)
expire yzcode 60(设置yzcode有效期为60秒)
ttl yzcode(查询yzcode剩余有效时间)
java中的使用:
1,在utils中封装一下redis命令,类名为RedisUtils,RedisUtils设置见https://blog.csdn.net/scorpio_meng/article/details/95459384
- /**
- * 设置键值的有效时间,以秒为单位
- * @param key
- * @param value
- * @param seconds
- * @param indexdb
- * @return
- */
- public static Long expire(String key,String value,int seconds,int indexdb) {
- Jedis jedis = null;
- try {
- jedis = jedisPool.getResource();
- jedis.select(indexdb);
- jedis.set(key,value);
- return jedis.expire(key,seconds);
- } catch (Exception e) {
- logger.error("expire错误日志:"+e.getMessage());
- return 0L;
- } finally {
- jedis.close();
- }
- }
-
- /**
- * 获取key值剩余的时间
- * @param key
- * @param indexdb
- * @return
- */
- public static Long ttl(String key,int indexdb) {
- Jedis jedis = null;
- try {
- jedis = jedisPool.getResource();
- jedis.select(indexdb);
- return jedis.ttl(key);
- } catch (Exception e) {
- logger.error("ttl错误日志:"+e.getMessage());
- return -1L;
- } finally {
- jedis.close();
- }
- }

2,接口中的调用
- @GetMapping(value = "/test_expire")
- public Long testExpire(){
- Long str = RedisUtils.expire("yzcode","876590",60,0);
- return str;
- }
- @GetMapping(value = "/test_ttl")
- public Long testTTL(){
- Long str = RedisUtils.ttl("yzcode",0);
- return str;
- }
3,测试一下结果
4,利用rpm工具查看结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。