2016-04-27 36 views
1

我有一個場景,我想用redis實現一個緩存機制。進一步詳細Redis過期並增加

首先我檢查使用client.get(),如果該值不存在的具體密鑰。我需要調用一個Web服務,它返回一個值並存儲爲密鑰的子對象。然後,我使用client.set()將此密鑰設置爲redis。現在這個密鑰需要過期,如果它已經設置了24小時以上,我該怎麼做?

這裏是鍵值的一個例子如下所示在redis的現在

parentValue:{ 
    child1:{ 
     serviceVal: "serviceVal", 
     counter: 0 
    }, 

    child2:{...}, 
    child3:{...} 
    .... 
} 

同樣當初始client.get(),執行,並且如果值存在,並且該特定的鍵不是招過期了。我想增加對象中的計數器,並在redis中更新此特定密鑰。我怎樣才能做到這一點?

回答

1

SET with NX and EX選項是您最簡單的解決方案。查看我正在使用的模塊here上的示例。

EX接受秒,所以你會想要86400秒24小時。

但對於遞增和到期你可能是最好的使用Redis的LUA腳本,像:

--[[ 
    key 1 -> key name 
    arg 1 -> expires in seconds 
    arg 2 -> incr by value 
]] 

-- Key exists so increment it 
if redis.call('exists',KEYS[1]) > 0 then 
    redis.call('incrby',KEYS[1],tonumber(ARGV[2])) 
    return 0 
else 
    -- key doesn't exist so create with an expiry and the incr amount 
    redis.call('setex',KEYS[1],tonumber(ARGV[1]),tonumber(ARGV[2])) 
    return 1 
end 

然後你只需要調用腳本使用密鑰,到期時間和多少遞增通過。