栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Jedis的Redis密钥过期通知

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Jedis的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*__:* 1onPMessage pattern __key*__:* __keyspace@0__:notify setonPMessage pattern __key*__:* __keyevent@0__:set notifyonPMessage pattern __key*__:* __keyspace@0__:notify expireonPMessage pattern __key*__:* __keyevent@0__:expire notifyonPMessage pattern __key*__:* __keyspace@0__:notify expiredonPMessage pattern __key*__:* __keyevent@0__:expired notify

现在是一个用例,您也对 过期密钥的 感兴趣。

注意:
Redis仅通过密钥空间事件的通知提供密钥过期时的密钥,密钥过期后值将丢失。为了使密钥的值过期,您可以使用影子密钥的棘手概念进行以下显示的操作:

当您创建通知键时,还要创建一个特殊的过期“影子”键(不要使实际的通知过期)。例如:

// set your key valueSET notify umq //set your "shadow" key, note the value here is irrelevantSET shadowkey:notify "" EX 10

//在频道 keyevent @ 0中 获取到期消息:expired //在“:”(或您决定使用的任何分隔符)上分割密钥,第二部分获取原始密钥

// Then get the value and do whatever with itGET notify// Then delete the keyDEL notify

请注意,没有使用shadowkey的值,因此您想使用最小的值,可以是空字符串“”。设置工作要多一些,但是上面的系统完全可以满足您的需求。开销是实际需要检索和删除密钥的一些额外命令,以及空密钥的存储成本。

否则,您必须以包含附加值的方式来准备密钥。

希望对您有帮助!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/386587.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号