Redis Key使用Jedis过期通知

Roc*_*Ray 13 java redis jedis

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

任何可能的插图代码将非常有用,因为我是redis的新手.

Kun*_*l-G 28

您只能使用pub-sub模型启动Redis Server

更改redis.conf到KEA的通知,密钥空间的事件(这取决于你的要求)Redis的文档中给出.Details http://redis.io/topics/notifications.

Redis Java Client(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


}
Run Code Online (Sandbox Code Playgroud)

订户:

****注意**jedis.psubscribe(new KeyExpiredListener(),"__ key*__:*"); - 此方法支持基于正则表达式模式的通道而jedis.subscribe(new KeyExpiredListener(),""__ keyyspace @ 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*__:*");

    }

}
Run Code Online (Sandbox Code Playgroud)

测试类:

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);

    }
}
Run Code Online (Sandbox Code Playgroud)

现在首先启动您的订阅服务器,然后运行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
Run Code Online (Sandbox Code Playgroud)

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

注意: Redis仅通过密钥空间事件通知提供密钥到期时的密钥,密钥到期后值将丢失.为了让你的密钥价值到期,你可以使用阴影键的棘手概念进行下面的工作:

创建通知密钥时,还要创建一个特殊的过期"影子"密钥(不要使实际通知失效).例如:

// set your key value
SET notify umq 
//set your "shadow" key, note the value here is irrelevant
SET shadowkey:notify "" EX 10 
Run Code Online (Sandbox Code Playgroud)

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

// Then get the value and do whatever with it
GET notify
// Then delete the key
DEL notify
Run Code Online (Sandbox Code Playgroud)

请注意,不使用shadowkey的值,因此您希望使用尽可能小的值,可以是空字符串"".设置工作要多一些,但上述系统完全符合您的需求.开销是一些额外的命令,用于实际检索和删除密钥以及空密钥的存储成本.

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

希望它能帮到你!