9、Redis处理过期keys的机制

写在前面的话:读书破万卷,编码如有神
--------------------------------------------------------------------
1、Redis处理过期key机制
  当client主动访问key的时,会先对key进行超时判断,过时的key会立即删除;另外redis会在后台,每秒10次的执行如下操作:随机选取100个key校验是否过期,如果有25个以上的key过期了,立刻额外随机选取下100个key。也就是说,如果过期的key不多,redis最多每秒回收200条左右,如果有超过25%的key过期了,它就会做得更多,这样即使从不被访问的数据,过期了也会被删除掉。
--------------------------------------------------------------------
2、处理过期keys的命令
2.1、expire : 设置过期时间。格式是:expire key值 秒数
2.2、expireat : 设置过期时间,格式是:expireat key值 到期的时间戳
2.3、ttl : 查看还有多少秒过期,格式是:ttl key值, -1表示永不过期,-2表示已经过期
2.4、persist : 设置成永不过期,格式是:persist key值 删除key的过期设置;另外使用set或者getset命令为键赋值的时候,也会清除键的过期时间。
2.5、pttl:查看还有多少毫秒过期,格式是:pttl key值
2.6、pexpire : 设置过期时间,格式是:pexpire key值 毫秒数
2.7、pexpireat : 设置过期时间,格式是:pexpireat key值 到期的时间戳
java代码如下:
 1 import redis.clients.jedis.Jedis;
 2 
 3 /**
 4  * 处理过期keys的命令
 5  */
 6 public class KeyExpireOperation {
 7     public static void main(String[] args) {
 8         Jedis jedis = new Jedis("127.0.0.1",6379);
 9         /**
10          * 示例1: expire : 设置过期时间。格式是:expire key值 秒数
11          */
12         Long expire = jedis.expire("k1", 6);
13         System.out.println("expire = " + expire);
14 
15         /**
16          * 示例2: expireat : 设置过期时间,格式是:expireat key值 到期的时间戳
17          */
18         Long expireAt = jedis.expireAt("k1", System.currentTimeMillis() + 100);
19         System.out.println("expireAt = " + expireAt);
20 
21         /**
22          * 示例3:ttl : 查看还有多少秒过期,格式是:ttl key值, -1表示永不过期,-2表示已经过期
23          */
24         Long ttl = jedis.ttl("k1");
25         System.out.println("ttl = " + ttl);
26 
27         /**
28          * 示例4:persist : 设置成永不过期,格式是:persist key值 删除key的过期设置;另外使用set或者getset命令为键赋值的时候,也会清除键的过期时间。
29          */
30         Long persist = jedis.persist("k1");
31         System.out.println("persist = " + persist);
32 
33         /**
34          * 示例5:pttl:查看还有多少毫秒过期,格式是:pttl key值
35          */
36         Long pttl = jedis.pttl("k1");
37         System.out.println("pttl = " + pttl);
38 
39         /**
40          * 已经不推荐使用了
41          * 示例6:pexpire : 设置过期时间,格式是:pexpire key值 毫秒数
42          */
43         Long pexpire = jedis.pexpire("k1", 1000);
44 
45         /**
46          * 示例7:pexpireat : 设置过期时间,格式是:pexpireat key值 到期的时间戳
47          */
48         Long pexpireAt = jedis.pexpireAt("k1", System.currentTimeMillis());
49         System.out.println("pexpireAt = " + pexpireAt);
50     }
51 }

猜你喜欢

转载自www.cnblogs.com/xinhuaxuan/p/9315851.html