[英]Redis Key expire notification with Jedis
當我的密鑰在Redis數據存儲區中過期時,我正在嘗試使用Redis實施過期密鑰通知。 Redis網站提供了一些有關http://redis.io/topics/notifications的描述,但是我無法找到使用Jedis這樣的redis java客戶端來進行此操作的示例?
任何可能的帶有插圖的代碼都將非常有用,因為它們是redis的新功能。
您只能使用pub-sub模型來啟動Redis Server
將redis.conf中的notify-keyspace-events更改為KEA(這取決於您的要求)。redis文檔http://redis.io/topics/notifications中提供了詳細信息 。
Redis Java客戶端(Jedis),請嘗試以下操作:
public class KeyExpiredListener extends JedisPubSub {
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
System.out.println("onPSubscribe "
+ pattern + " " + subscribedChannels);
}
@Override
public void onPMessage(String pattern, String channel, String message) {
System.out
.println("onPMessage pattern "
+ pattern + " " + channel + " " + message);
}
//add other Unimplemented methods
}
****注意** jedis。 psubscribe (新的KeyExpiredListener(),“ __ key * __:*”); -此方法支持基於正則表達式模式的通道,而jedis。 訂閱 (new KeyExpiredListener(),“” __keyspace @ 0 __:notify“);-此方法使用完整/確切的頻道名稱
public class Subscriber {
public static void main(String[] args) {
JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
Jedis jedis = pool.getResource();
jedis.psubscribe(new KeyExpiredListener(), "__key*__:*");
}
}
public class TestJedis {
public static void main(String[] args) {
JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
Jedis jedis = pool.getResource();
jedis.set("notify", "umq");
jedis.expire("notify", 10);
}
}
現在首先啟動您的訂閱服務器,然后運行TestJedis。您將看到以下輸出:
onPSubscribe __key*__:* 1
onPMessage pattern __key*__:* __keyspace@0__:notify set
onPMessage pattern __key*__:* __keyevent@0__:set notify
onPMessage pattern __key*__:* __keyspace@0__:notify expire
onPMessage pattern __key*__:* __keyevent@0__:expire notify
onPMessage pattern __key*__:* __keyspace@0__:notify expired
onPMessage pattern __key*__:* __keyevent@0__:expired notify
現在是一個用例,您也對過期密鑰的值感興趣。
注意: Redis僅通過密鑰空間事件的通知來提供密鑰過期時的密鑰,密鑰過期后值將丟失。 為了使密鑰上的值過期,您可以使用影子密鑰的棘手概念進行以下顯示的操作:
當您創建通知鍵時,還要創建一個特殊的過期“影子”鍵(不要使實際的通知過期)。 例如:
// set your key value
SET notify umq
//set your "shadow" key, note the value here is irrelevant
SET shadowkey:notify "" EX 10
//在通道keyevent @ 0中獲取到期消息:expired //在“:”(或您決定使用的任何分隔符)上分割密鑰,第二部分獲取原始密鑰
// Then get the value and do whatever with it
GET notify
// Then delete the key
DEL notify
請注意,沒有使用shadowkey的值,因此您想使用最小的值,可以是空字符串“”。 設置工作要多一些,但是上面的系統完全可以滿足您的需求。 開銷是實際需要檢索和刪除密鑰的一些額外命令,以及空密鑰的存儲成本。
否則,您必須以包含附加值的方式准備密鑰。
希望對您有幫助!
這可能對您有幫助。
JedisPool jedisPool=null;
JedisPoolConfig poolConfig = null;
try {
poolConfig=new JedisPoolConfig();
jedisPool = new JedisPool(poolConfig,"127.0.0.1" /*Host IP*/,1234 /*Port*/, 0);
Jedis jedis=jedisPool.getResource();
jedis.expire("KeyName", 10 /*Key Expires in 10 seconds*/);
} catch (Exception e) {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.