JAVA realizes the monitoring trigger of redis timeout invalid key

Expired events are distributed through Redis's subscription and publishing functions (pub/sub).

As for the monitoring of timeout, you do not need to publish it yourself, only modify the configuration file redis.conf: notify-keyspace-events  Ex , the default is notify-keyspace-events  "" 


# K keyspace notifications, prefixed with __keyspace@<db>__
# E key event notification, prefixed with __keysevent@<db>__
# g del , expipre , rename and other type-independent general command notifications, ...
# $StringCommand
# l List command
# s Set command
# h Hash command
# z ordered set command
# x expiration event (generated every time the key expires)
# e eviction event (generated when the key is full and cleared)
# A alias for g$lshzxe, so "AKE" means all events

After modifying the configuration file, redis will monitor the data set to expire, and when the data expires, it will be deleted from redis:


1. First write a listener:

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



}


 
 

2. Subscribers:

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

    }

}


 
 

3. Test class:

public class TestJedis {

    public static void main(String[] args) {
        JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");

        Jedis jedis = pool.getResource();
        jedis.set("notify", "Sina Weibo: Little Leaf is not funny");
        jedis.expire("notify", 10);

    }
}


4. Results:

Start the subscriber first, then execute the test class, and then wait for 10 seconds before you can get the callback in the method of the listening class. When the main one is needed very much, the default pipeline for expired monitoring is __keyevent@0__:expired, the 0 after Aite indicates which database is the first, and the default database of redis is 0~15, a total of 16 databases. So if the database you store is 2, then the pipeline for data reception is __keyevent@2__:expired


5. If you have any questions, please come to Sina Weibo to find me, ID: Xiao Ye is not funny at all


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324885337&siteId=291194637