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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM