importredis.clients.jedis.Jedis;importredis.clients.jedis.exceptions.JedisConnectionException;importjava.util.Set;importjava.util.concurrent.Executors;importjava.util.concurrent.ScheduledExecutorService;importjava.util.concurrent.TimeUnit;publicclassRedisScheduledDeleteExample{publicstaticvoidmain(String[] args){// 连接到本地的Redis服务Jedis jedis =newJedis("localhost",6379);try{// 设置键值对,并设置过期时间为10秒
jedis.set("key1","value1");
jedis.expire("key1",10);// 使用ScheduledExecutorService来定期检查并删除过期数据ScheduledExecutorService executor =Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(()->{// 获取所有键Set<String> keys = jedis.keys("*");for(String key : keys){// 检查键是否过期,过期则删除if(jedis.ttl(key)==-2){
jedis.del(key);System.out.println("Key "+ key +" has expired and has been deleted.");}}},0,1,TimeUnit.SECONDS);// 每秒检查一次// 等待一段时间,以便观察定时删除的效果try{Thread.sleep(15000);}catch(InterruptedException e){
e.printStackTrace();}// 关闭连接
jedis.close();
executor.shutdown();}catch(JedisConnectionException e){System.err.println("Could not connect to Redis. Please make sure that the Redis server is running.");}}}
importredis.clients.jedis.Jedis;importredis.clients.jedis.exceptions.JedisConnectionException;publicclassRedisLazyDeleteExample{publicstaticvoidmain(String[] args){// 连接到本地的Redis服务Jedis jedis =newJedis("localhost",6379);try{// 设置键值对,并设置过期时间为10秒
jedis.set("key1","value1");
jedis.expire("key1",10);// 获取数据时检查数据是否过期,如果过期则删除String value = jedis.get("key1");if(value ==null){System.out.println("Key does not exist.");}else{System.out.println("Value of key1: "+ value);Long ttl = jedis.ttl("key1");if(ttl !=-2&& ttl !=-1){System.out.println("Key is not expired.");}else{
jedis.del("key1");System.out.println("Key has expired and has been deleted.");}}// 关闭连接
jedis.close();}catch(JedisConnectionException e){System.err.println("Could not connect to Redis. Please make sure that the Redis server is running.");}}}