Redis Lettuce java library notification on element expire

Viewed 2068

Can I manage redis notifications with Lettuce? I can't find any example or doc on it. I simply need to have some notification/callback in my java code when elements expire in Redis.

Let me put an example... I'm sorry, reading the Lettuce doc won't help me (and I I've taken some time)

Imagine I have a namespace of objects where I execute get and set commands:

"ONLINEUSERS:userid"

I add a user that will expire in an hour:

syncCommands.setex("ONLINEUSERS:"+userid,3600, mapper.writeValueAsString(userObject));

How can I have a method in my java code executed after those 3600 seconds make the key expire?

I mean... In the doc, the commands are:

StatefulRedisPubSubConnection<String, String> connection = client.connectPubSub()
connection.addListener(new RedisPubSubListener<String, String>() { ... })

RedisPubSubAsyncCommands<String, String> async = connection.async();
RedisFuture<Void> future = async.subscribe("channel");

// application flow continues

What would be the values for String, String array and "channel" parameter matching my expire event for my key namespace?

1 Answers

I was facing a similar issue.

First, you need to make sure that your Redis server is configured to publish key-space event notifications. By default, this is disabled. Usually, the configuration file is located in /etc/redis/redis.conf. The property to look at is called notify-keyspace-events. If you want your Redis server to publish events for expired and deleted keys, you can pass a value such as Ex to the last property. Think to restart your Redis server once you applied a configuration change.

Second, you need to subscribe to the channel with name __keyevent@0__:expired from your Redis client instance.

Related