Redis Key使用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://dis.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 } 

订户:

****注意** 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*__:*"); } } 

测试类:

 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中获取过期消息:过期//在“:”(或您决定使用的任何分隔符)上拆分键,取第二部分获取原始密钥

 // 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) { }