---
title: "记录一下redisson监听key过期事件功能"
author: "hellohank"
date: "2022-02-18T17:40:22Z"
tags: []
categories: ["开源软件"]
slug: "redisson-key"
draft: false
lastmod: "2022-02-18T17:40:22Z"
id: 2524409
url: "https://hellohank.iteye.com/blog/2524409"
---

使用redisson监听key过期，需要两步操作：

1、开启redis服务端的事件广播功能。

如果是自建的，则直接在redis.conf中增加或修改（修改后重启redis）：

```
notify-keyspace-events "KEx"
```

    具体可选的选项如下（所以，上面的KEx可以看下面的含义）：

    

```
 K     Keyspace events, published with __keyspace@<db>__ prefix.
 E     Keyevent events, published with __keyevent@<db>__ prefix.
 g     Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
 $     String commands
 l     List commands
 s     Set commands
 h     Hash commands
 z     Sorted set commands
 x     Expired events (events generated every time a key expires)
 e     Evicted events (events generated when a key is evicted for maxmemory)
 A     Alias for g$lshzxe, so that the "AKE" string means all the events.
```

 

如果是阿里云redis，则可以到阿里redis的管理界面操作。

 

2、项目中添加监听事件（监听redis事件的行为，各个组件，如jedis等都有自己的方式，自己百度，这里是记录redisson的方式）：

```
public static void main(String[] args) {
        int db = 2;
        RedissonClient redissonClient = createClient(db);
        RTopic topic = redissonClient.getTopic("__keyevent@" + db + "__:expired", new StringCodec());
        topic.addListener(String.class, new MessageListener() {
            @Override
            public void onMessage(CharSequence channel, Object msg) {
                System.out.println("收取到过期的事件:" + channel + "; Thread: " + Thread.currentThread().toString());
                System.out.println("过期的key="+msg);
            }
        });
        String key = "test_expire_listen";
        Object value = "val";
        RBucket bucket = redissonClient.getBucket(key);
        bucket.set(JSON.toJSONString(value), 5, TimeUnit.SECONDS);
        bucket.expire(6,TimeUnit.SECONDS);
    }

    private static RedissonClient createClient(int db) {
        Config config = new Config();
        config.setCodec(new StringCodec());
        config.useSingleServer()
                .setAddress("redis://127.0.0.1:6379")
                .setPassword("******")
                .setConnectionPoolSize(500)
                .setIdleConnectionTimeout(10000)
                .setTimeout(3000)
                .setConnectTimeout(30000)
                .setRetryAttempts(3)
                .setRetryInterval(1000)
                .setDnsMonitoringInterval(-1)
                .setPingConnectionInterval(10000)
                .setDatabase(db);
        return Redisson.create(config);
    }
```