首页 > 技术文章 > redis 超时失效key 的监听触发使用

pypua 2019-06-17 17:17 原文

redis自2.8.0之后版本提供Keyspace Notifications功能,允许客户订阅Pub / Sub频道,以便以某种方式接收影响Redis数据集的事件。

可能收到的事件的例子如下: 
所有影响给定键的命令。 
所有接收LPUSH操作的密钥。 
所有密钥在数据库中过期0。

因为 Redis 目前的订阅与发布功能采取的是发送即忘(fire and forget)策略, 所以如果你的程序需要可靠事件通知(reliable notification of events), 那么目前的键空间通知可能并不适合你:当订阅事件的客户端断线时, 它会丢失所有在断线期间分发给它的事件。并不能确保消息送达。未来有计划允许更可靠的事件传递,但可能这将在更一般的层面上解决,或者为Pub / Sub本身带来可靠性,或者允许Lua脚本拦截Pub / Sub消息来执行诸如推送将事件列入清单。

事件类型

对于每个修改数据库的操作,键空间通知都会发送两种不同类型的事件消息:keyspace 和 keyevent。以 keyspace 为前缀的频道被称为键空间通知(key-space notification), 而以 keyevent 为前缀的频道则被称为键事件通知(key-event notification)。

事件是用  __keyspace@DB__:KeyPattern 或者  __keyevent@DB__:OpsType 的格式来发布消息的。
DB表示在第几个库;KeyPattern则是表示需要监控的键模式(可以用通配符,如:__key*__:*);OpsType则表示操作类型。因此,如果想要订阅特殊的Key上的事件,应该是订阅keyspace。
比如说,对 0 号数据库的键 mykey 执行 DEL 命令时, 系统将分发两条消息, 相当于执行以下两个 PUBLISH 命令:
PUBLISH __keyspace@0__:sampleKey del
PUBLISH __keyevent@0__:del sampleKey
订阅第一个频道 __keyspace@0__:mykey 可以接收 0 号数据库中所有修改键 mykey 的事件, 而订阅第二个频道 __keyevent@0__:del 
则可以接收 0 号数据库中所有执行 del 命令的键。

开启配置

开启配置

键空间通知通常是不启用的,因为这个过程会产生额外消耗。所以在使用该特性之前,请确认一定是要用这个特性的,然后修改配置文件,或使用config配置。相关配置项如下:

字符发送通知
K 键空间通知,所有通知以 keyspace@ 为前缀,针对Key
E 键事件通知,所有通知以 keyevent@ 为前缀,针对event
g DEL 、 EXPIRE 、 RENAME 等类型无关的通用命令的通知
$ 字符串命令的通知
l 列表命令的通知
s 集合命令的通知
h 哈希命令的通知
z 有序集合命令的通知
x 过期事件:每当有过期键被删除时发送
e 驱逐(evict)事件:每当有键因为 maxmemory 政策而被删除时发送
A 参数 g$lshzxe 的别名,相当于是All

 

 

 

 

 

 

 

 

 

 

 

输入的参数中至少要有一个 K 或者 E , 否则的话, 不管其余的参数是什么, 都不会有任何通知被分发。上表中斜体的部分为通用的操作或者事件,而黑体则表示特定数据类型的操作。配置文件中修改 notify-keyspace-events “Kx”,注意:这个双引号是一定要的,否则配置不成功,启动也不报错。例如,“Kx”表示想监控某个Key的失效事件。

也可以通过config配置:CONFIG set notify-keyspace-events Ex (但非持久化)

Redis 使用以下两种方式删除过期的键:
1.当一个键被访问时,程序会对这个键进行检查,如果键已经过期,那么该键将被删除。
2.底层系统会在后台查找并删除那些过期的键,从而处理那些已经过期、但是不会被访问到的键。
当过期键被以上两个程序的任意一个发现、 并且将键从数据库中删除时, Redis 会产生一个 expired 通知。
Redis 并不保证生存时间(TTL)变为 0 的键会立即被删除: 如果程序没有访问这个过期键, 或者带有生存时间的键非常多的话,
那么在键的生存时间变为 0 , 直到键真正被删除这中间,
可能会有一段比较显著的时间间隔。 因此, Redis 产生 expired 通知的时间为过期键被删除的时候, 而不是键的生存时间变为
0 的时候。

由于通知收到的是redis key,value已经过期,无法收到,所以需要在key上标记业务数据。

 

 redis 超时失效key 的监听触发

 

1. 事件通过 Redis 的订阅与发布功能(pub/sub)来进行分发,故需要订阅 __keyevent@0__:expired 通道

0表示db0 根据自己的dbindex选择合适的数字

2. 修改 redis.conf 文件 

修改 notify-keyspace-events Ex 

复制代码
复制代码
# K    键空间通知,以__keyspace@<db>__为前缀
# E    键事件通知,以__keysevent@<db>__为前缀
# g    del , expipre , rename 等类型无关的通用命令的通知, ...
# $    String命令
# l    List命令
# s    Set命令
# h    Hash命令
# z    有序集合命令
# x    过期事件(每次key过期时生成)
# e    驱逐事件(当key在内存满了被清除时生成)
# A    g$lshzxe的别名,因此”AKE”意味着所有的事件
复制代码
复制代码

 

3. 重启redis , 即可测试失效事件的触发, 监听获取的值为 key

<java>

4.  首先需要一个消息监听器类  RedisSubListener

RedisSubListener.java
package cn.maitian.maimai.cache.message.sub;

import cn.maitian.bss.duty.privilege.utils.SpringContextHolder;
import cn.maitian.maimai.cache.client.MaimaiJedis;
import cn.maitian.maimai.cache.keys.RedisKeys;
import cn.maitian.maimai.cache.model.RedisKeyspaceNotifiRecord;
import cn.maitian.maimai.cache.service.RedisKeyspaceNotifiRecordIService;
import cn.maitian.maimai.core.exception.AppSysException;
import cn.maitian.maimai.core.util.AppStringUtils;
import cn.maitian.maimai.schedule.utils.JobUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import redis.clients.jedis.JedisPubSub;

import java.util.Date;

/**
 * Redis 发布订阅模型(Pub/Sub)的订阅服务监听器
 *
 * @author 
 * @version V1.0
 * @company 
 * @date 
 */
public class RedisSubListener extends JedisPubSub {

    /**
     * 日志
     */
    protected final Logger logger = Logger.getLogger(getClass());

    private RedisKeyspaceNotifiRecordIService redisKeyspaceNotifiRecordIService;

    /**
     *
     * @Title: onMessage
     * @Description: 取得订阅的消息后的处理
     * @param channel
     *            频道
     * @param message
     *            消息内容
     *
     * @author 
     * @date 
     */
    @Override
    public void onMessage(String channel, String message) {
        logger.info("channel{" + channel + "}message{" + message + "}");
    }

    /**
     *
     * @Title: onPMessage
     * @Description: 取得按表达式的方式订阅的消息后的处理
     *
     * @author 
     * @date 
     */
    public void onPMessage(String pattern, String channel, String message) {
        logger.info("Redis订阅监听超时通知开始pattern{" + pattern + "}channel{" + channel + "}message{" + message + "}");
        long starTime = System.currentTimeMillis();
        if (AppStringUtils.isEmpty(message)) {
            logger.info("Redis订阅监听超时通知,message为空");
            return;
        }
        RedisKeyspaceNotifiRecord record = null;
        String keyId;
        try {
            if (message.startsWith(RedisKeys.REDIS_LOCK_KEY_STRING)) {
                logger.info("Redis订阅监听超时通知,此key值不需要进行订阅处理");
                return;
            }
            keyId = message.substring(message.lastIndexOf(":") + 1);
            long result = MaimaiJedis.setnx(RedisKeys.REDIS_LOCK_KEY_STRING + keyId,RedisKeys.REDIS_LOCK_KEY_STRING + keyId);
            if (result==0) {
                logger.info("Redis订阅监听超时通知,此key已被设置,请勿重复设置");
                return;
            }
            record = redisKeyspaceNotifiRecordIService.findById(keyId);
            if (record == null) {
//                throw new AppSysException("Redis订阅监听超时通知,找不到记录id{" + keyId + "}");
                logger.error("Redis订阅监听超时通知,找不到记录id{" + keyId + "}");
                return;
            }
            record.setBeginTime(new Date());
            if (AppStringUtils.isEmpty(record.getServiceClass())) {
                throw new AppSysException("Redis订阅监听超时通知,RedisKeyspaceNotifiRecord中必须包含ServiceClass");
            }
            Object object = SpringContextHolder.getBean(Class.forName(record.getServiceClass()));
            String serviceMethod = record.getServiceMethod();
            Object[] params;
            if (AppStringUtils.isEmpty(record.getServiceParams())) {
                params = new Object[] {};
            } else {
                params = JSONObject.parseArray(record.getServiceParams()).toArray();
            }
            if (object != null && !AppStringUtils.isEmpty(serviceMethod)) {
                JobUtils.invokeMethod(object, serviceMethod, params);
                record.setStatus(RedisKeyspaceNotifiRecord.STATUS_SUCCESS_EXECUTE);// 执行成功
            }
        } catch (AppSysException e) {
            if (record != null) {
                record.setStatus(RedisKeyspaceNotifiRecord.STATUS_FAIL_EXECUTE);// 执行失败
            }
            e.printStackTrace();
            logger.info("Redis订阅监听超时通知,出现异常{" + e.getCode() + "}", e);
        } catch (Exception e) {
            if (record != null) {
                record.setStatus(RedisKeyspaceNotifiRecord.STATUS_FAIL_EXECUTE);// 执行失败
            }
            e.printStackTrace();
            logger.info("Redis订阅监听超时通知,出现异常", e);
        } finally {
            if (record != null) {
                record.setEndTime(new Date());
                redisKeyspaceNotifiRecordIService.saveOrUpdate(record);
            }
        }
        long endTime = new Date().getTime();
        logger.info("Redis订阅监听超时通知完成pattern{" + pattern + "}channel{" + channel + "}message{" + message + "}共耗时{"
                + (endTime - starTime) / 1000 + "}秒");
    }

    /**
     * @param redisKeyspaceNotifiRecordIService
     *            the redisKeyspaceNotifiRecordIService to set
     */
    public void setRedisKeyspaceNotifiRecordIService(
            RedisKeyspaceNotifiRecordIService redisKeyspaceNotifiRecordIService) {
        this.redisKeyspaceNotifiRecordIService = redisKeyspaceNotifiRecordIService;
    }

}

5.Redis订阅指定的频道(此类用于订阅Redis的键值超时事件)
RedisKeySpaceNotification.java
package cn.maitian.maimai.cache.message.sub;

import cn.maitian.maimai.cache.client.MaimaiJedis;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Redis订阅指定的频道(此类用于订阅Redis的键值超时事件)
 * 
 * @author 
 * @version V1.0
 * @company 
 * @date 
 */
public class RedisKeySpaceNotification implements InitializingBean, DisposableBean {

    /**
     * 是否开启Redis键值超时通知服务(默认打开)
     */
    private static boolean isRedisActiveKeySpaceNotification = true;

    /**
     * 日志
     */
    protected final Logger logger = Logger.getLogger(getClass());

    private RedisSubListener redisSubListener;

    @Override
    public void destroy() throws Exception {
        // 销毁
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (isRedisActiveKeySpaceNotification) {
            logger.error("Redis订阅的键值超时事件已启动-----------------------------------");
            JedisPool jedisPool = MaimaiJedis.getMaiMaiJedisPool();
            final Jedis jedis = jedisPool.getResource();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    jedis.psubscribe(redisSubListener, "__keyevent@*__:expired");
                }
            }).start();
        }
    }

    /**
     * @param redisSubListener
     *            the redisSubListener to set
     */
    public void setRedisSubListener(RedisSubListener redisSubListener) {
        this.redisSubListener = redisSubListener;
    }
}

 

 

推荐阅读