小编典典

Jedis的Redis密钥过期通知

redis

当我的密钥在Redis数据存储区中过期时,我正在尝试使用Redis实施过期密钥通知。redis网站提供了一些有关http://redis.io/topics/notifications的描述,但是我无法找到任何示例,例如使用Jedis的redis
java客户端如何做到这一点?

任何可能的带有插图的代码都将非常有用,因为它们是redis的新功能。


阅读 419

收藏
2020-06-20

共1个答案

小编典典

您只能使用 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的值,因此您想使用最小的值,可以是空字符串“”。设置工作要多一些,但是上面的系统完全可以满足您的需求。开销是实际需要检索和删除密钥的一些额外命令,以及空密钥的存储成本。

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

希望对您有帮助!

2020-06-20