引入 jedis
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.5.1</version>
</dependency>
java代码
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;
import java.util.List;
public class Main {
public static void main(String[] args) {
JedisPool pool = new JedisPool("127.0.0.1");
//订阅过期事件
new Thread(() -> {
Jedis jedis = pool.getResource();
String parameter = "notify-keyspace-events";
List<String> notify = jedis.configGet(parameter);
if ("".equals(notify.get(1))) jedis.configSet(parameter, "Ex");
jedis.psubscribe(new MyJedisPubSub(), "__keyevent@0__:expired");
}).start();
//储存数据 5秒后过期
new Thread(() -> pool.getResource().setex("key", 5, "hello word")).start();
}
}
/**
* 事件回调
*/
class MyJedisPubSub extends JedisPubSub {
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
System.out.println("订阅事件-> "
+ pattern + " " + subscribedChannels);
}
@Override
public void onPMessage(String pattern, String channel, String key) {
System.out.println("收到消息-> "
+ pattern + " " + channel + " " + key);
}
}