首页 > 数据库 >Redis 过期监听 + 加阻塞队列

Redis 过期监听 + 加阻塞队列

时间:2023-08-18 10:23:03浏览次数:41  
标签:event __ generates 过期 Redis 监听 generated key events

https://redis.io/docs/manual/keyspace-notifications/

 

简单一句话就是要订阅key失效事件

 

应用场景:在线客服中开启会话后,如果客户一段时间未回复,则结束会话。为了保证会话结束的时效性,通过redis 订阅key失效事件处理

 

 

 

 

 

 

 

 配置 notify-keyspace-events Ex

 

key失效后就会发布消息,业务中订阅这个topic 

    @Bean
    public RedisConsumer initRedisConsumer() {
        System.out.println(RedisManager.set("aabbcc", "123", 10));
        return new RedisConsumer("__keyevent@7__:expired", (k,v)->System.out.println("接收到["+k+"]的消息:" + v), false);
    }

 

收到消息:

接收到[__keyevent@7__:expired]的消息:aabbcc

 

修改配置需要重启,消息不丢失

 

补充:因为被动失效时效性不能保证完全实时,可以起一个定时任务去查询key,主动触发检测

 补充2:主动删除key,不会触发失效通知

 

 

 

 

 

 

 

 

 

 

 

 

Redis keyspace notifications

Monitor changes to Redis keys and values in real time

Keyspace notifications allow clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.

Examples of events that can be received are:

  • All the commands affecting a given key.
  • All the keys receiving an LPUSH operation.
  • All the keys expiring in the database 0.

Note: Redis Pub/Sub is fire and forget that is, if your Pub/Sub client disconnects, and reconnects later, all the events delivered during the time the client was disconnected are lost.

Type of events

Keyspace notifications are implemented by sending two distinct types of events for every operation affecting the Redis data space. For instance a DEL operation targeting the key named mykey in database 0 will trigger the delivering of two messages, exactly equivalent to the following two PUBLISH commands:

PUBLISH __keyspace@0__:mykey del
PUBLISH __keyevent@0__:del mykey

The first channel listens to all the events targeting the key mykey and the other channel listens only to del operation events on the key mykey

The first kind of event, with keyspace prefix in the channel is called a Key-space notification, while the second, with the keyevent prefix, is called a Key-event notification.

In the previous example a del event was generated for the key mykey resulting in two messages:

  • The Key-space channel receives as message the name of the event.
  • The Key-event channel receives as message the name of the key.

It is possible to enable only one kind of notification in order to deliver just the subset of events we are interested in.

Configuration

By default keyspace event notifications are disabled because while not very sensible the feature uses some CPU power. Notifications are enabled using the notify-keyspace-events of redis.conf or via the CONFIG SET.

Setting the parameter to the empty string disables notifications. In order to enable the feature a non-empty string is used, composed of multiple characters, where every character has a special meaning according to the following table:

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
t     Stream commands
d     Module key type events
x     Expired events (events generated every time a key expires)
e     Evicted events (events generated when a key is evicted for maxmemory)
m     Key miss events (events generated when a key that doesn't exist is accessed)
n     New key events (Note: not included in the 'A' class)
A     Alias for "g$lshztxed", so that the "AKE" string means all the events except "m".

At least K or E should be present in the string, otherwise no event will be delivered regardless of the rest of the string.

For instance to enable just Key-space events for lists, the configuration parameter must be set to Kl, and so forth.

You can use the string KEA to enable most types of events.

Events generated by different commands

Different commands generate different kind of events according to the following list.

  • DEL generates a del event for every deleted key.
  • RENAME generates two events, a rename_from event for the source key, and a rename_to event for the destination key.
  • MOVE generates two events, a move_from event for the source key, and a move_to event for the destination key.
  • COPY generates a copy_to event.
  • MIGRATE generates a del event if the source key is removed.
  • RESTORE generates a restore event for the key.
  • EXPIRE and all its variants (PEXPIREEXPIREATPEXPIREAT) generate an expire event when called with a positive timeout (or a future timestamp). Note that when these commands are called with a negative timeout value or timestamp in the past, the key is deleted and only a del event is generated instead.
  • SORT generates a sortstore event when STORE is used to set a new key. If the resulting list is empty, and the STORE option is used, and there was already an existing key with that name, the result is that the key is deleted, so a del event is generated in this condition.
  • SET and all its variants (SETEXSETNX,GETSET) generate set events. However SETEX will also generate an expire events.
  • MSET generates a separate set event for every key.
  • SETRANGE generates a setrange event.
  • INCRDECRINCRBYDECRBY commands all generate incrby events.
  • INCRBYFLOAT generates an incrbyfloat events.
  • APPEND generates an append event.
  • LPUSH and LPUSHX generates a single lpush event, even in the variadic case.
  • RPUSH and RPUSHX generates a single rpush event, even in the variadic case.
  • RPOP generates an rpop event. Additionally a del event is generated if the key is removed because the last element from the list was popped.
  • LPOP generates an lpop event. Additionally a del event is generated if the key is removed because the last element from the list was popped.
  • LINSERT generates an linsert event.
  • LSET generates an lset event.
  • LREM generates an lrem event, and additionally a del event if the resulting list is empty and the key is removed.
  • LTRIM generates an ltrim event, and additionally a del event if the resulting list is empty and the key is removed.
  • RPOPLPUSH and BRPOPLPUSH generate an rpop event and an lpush event. In both cases the order is guaranteed (the lpush event will always be delivered after the rpop event). Additionally a del event will be generated if the resulting list is zero length and the key is removed.
  • LMOVE and BLMOVE generate an lpop/rpop event (depending on the wherefrom argument) and an lpush/rpush event (depending on the whereto argument). In both cases the order is guaranteed (the lpush/rpush event will always be delivered after the lpop/rpop event). Additionally a del event will be generated if the resulting list is zero length and the key is removed.
  • HSETHSETNX and HMSET all generate a single hset event.
  • HINCRBY generates an hincrby event.
  • HINCRBYFLOAT generates an hincrbyfloat event.
  • HDEL generates a single hdel event, and an additional del event if the resulting hash is empty and the key is removed.
  • SADD generates a single sadd event, even in the variadic case.
  • SREM generates a single srem event, and an additional del event if the resulting set is empty and the key is removed.
  • SMOVE generates an srem event for the source key, and an sadd event for the destination key.
  • SPOP generates an spop event, and an additional del event if the resulting set is empty and the key is removed.
  • SINTERSTORESUNIONSTORESDIFFSTORE generate sinterstoresunionstoresdiffstore events respectively. In the special case the resulting set is empty, and the key where the result is stored already exists, a del event is generated since the key is removed.
  • ZINCR generates a zincr event.
  • ZADD generates a single zadd event even when multiple elements are added.
  • ZREM generates a single zrem event even when multiple elements are deleted. When the resulting sorted set is empty and the key is generated, an additional del event is generated.
  • ZREMBYSCORE generates a single zrembyscore event. When the resulting sorted set is empty and the key is generated, an additional del event is generated.
  • ZREMBYRANK generates a single zrembyrank event. When the resulting sorted set is empty and the key is generated, an additional del event is generated.
  • ZDIFFSTOREZINTERSTORE and ZUNIONSTORE respectively generate zdiffstorezinterstore and zunionstore events. In the special case the resulting sorted set is empty, and the key where the result is stored already exists, a del event is generated since the key is removed.
  • XADD generates an xadd event, possibly followed an xtrim event when used with the MAXLEN subcommand.
  • XDEL generates a single xdel event even when multiple entries are deleted.
  • XGROUP CREATE generates an xgroup-create event.
  • XGROUP CREATECONSUMER generates an xgroup-createconsumer event.
  • XGROUP DELCONSUMER generates an xgroup-delconsumer event.
  • XGROUP DESTROY generates an xgroup-destroy event.
  • XGROUP SETID generates an xgroup-setid event.
  • XSETID generates an xsetid event.
  • XTRIM generates an xtrim event.
  • PERSIST generates a persist event if the expiry time associated with key has been successfully deleted.
  • Every time a key with a time to live associated is removed from the data set because it expired, an expired event is generated.
  • Every time a key is evicted from the data set in order to free memory as a result of the maxmemory policy, an evicted event is generated.
  • Every time a new key is added to the data set, a new event is generated.

IMPORTANT all the commands generate events only if the target key is really modified. For instance an SREM deleting a non-existing element from a Set will not actually change the value of the key, so no event will be generated.

If in doubt about how events are generated for a given command, the simplest thing to do is to watch yourself:

$ redis-cli config set notify-keyspace-events KEA
$ redis-cli --csv psubscribe '__key*__:*'
Reading messages... (press Ctrl-C to quit)
"psubscribe","__key*__:*",1

At this point use redis-cli in another terminal to send commands to the Redis server and watch the events generated:

"pmessage","__key*__:*","__keyspace@0__:foo","set"
"pmessage","__key*__:*","__keyevent@0__:set","foo"
...

Timing of expired events

Keys with a time to live associated are expired by Redis in two ways:

  • When the key is accessed by a command and is found to be expired.
  • Via a background system that looks for expired keys in the background, incrementally, in order to be able to also collect keys that are never accessed.

The expired events are generated when a key is accessed and is found to be expired by one of the above systems, as a result there are no guarantees that the Redis server will be able to generate the expired event at the time the key time to live reaches the value of zero.

If no command targets the key constantly, and there are many keys with a TTL associated, there can be a significant delay between the time the key time to live drops to zero, and the time the expired event is generated.

Basically expired events are generated when the Redis server deletes the key and not when the time to live theoretically reaches the value of zero.

Events in a cluster

Every node of a Redis cluster generates events about its own subset of the keyspace as described above. However, unlike regular Pub/Sub communication in a cluster, events' notifications are not broadcasted to all nodes. Put differently, keyspace events are node-specific. This means that to receive all keyspace events of a cluster, clients need to subscribe to each of the nodes.

@history

  • >= 6.0: Key miss events were added.
  • >= 7.0: Event type new added

 

标签:event,__,generates,过期,Redis,监听,generated,key,events
From: https://www.cnblogs.com/zno2/p/16621272.html

相关文章

  • Redis专题-秒杀
    Redis专题-并发/秒杀开局一张图,内容全靠“编”。昨天晚上在群友里看到有人在讨论库存并发的问题,看到这里我就决定写一篇关于redis秒杀的文章。1、理论部分我们看看一般我们库存是怎么出问题的其实redis提供了两种解决方案:加锁和原子操作。1.1、加锁加锁:其实非常常见,读取......
  • 虹科分享|Redis Stack不想再让开发人员受苦了!
    你想构建能提供实时体验的应用程序吗?那么你怎么可以不拥有一个能以最快响应时间处理任何请求的数据库?无论是简单的对象检索、搜索还是复杂的聚合,在一毫秒之内便完成。领先的Redis模块华丽变身为RedisStack来帮你啦!什么是RedisStackRedisStack:整合Redis模块的功能为了简化开发人......
  • 虹科分享|Redis Stack不想再让开发人员受苦了!
    什么是RedisStackRedisStack:整合Redis模块的功能为了简化开发人员对较新的Redis模块及其提供的功能的体验,同时简化支持其功能的文档和客户端。以帮助开发人员从开始使用Redis的那一刻起,就能充分提高工作效率。RedisStack诞生了。RedisStack将较新的Redis模块整合到一......
  • 在 Spring Boot 中通过定时任务实现本地 Redis 数据同步到阿里云 Redis
    添加依赖在项目的pom.xml文件中,添加SpringBootStarter和Redis相关的依赖。<!--SpringBootStarter--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency>......
  • liunx安装和卸载redis
    1下载安装1下载wgethttp://download.redis.io/releases/redis-6.2.9.tar.gz2解压tar-xzfredis-6.2.9.tar.gz3建立软连接ln-sredis-6.2.9redis4切换到redis路径下,解压安装cdredismake&&makeinstall在src目录下可以看到#redis-server--->redis服务器#red......
  • 测试面试 | 怎么查看redis | linux
    总的来说就是查服务、查端口、查进程。1、查看服务状态servicestatusnginx / systemctlstatusredis 直接可以看到版本号pid 2、lsof-i:3306一般都是一个服务一个端口,不能两个服务一个,占用了,就起不来了. 3、ps-ef|grepredis  ......
  • redis:info指令
    学习自:Redis之info指令_redis-cliinfo_多动手,勤思考的博客-CSDN博客官网:INFO|Redis场景redis提供了info指令,可以帮助用户查询redis服务运行期间内部的参数以及实时信息,根据这些信息可以帮助用户诊断问题或查看服务负载、内存压力等信息。info指令显示的信息繁多,分为9大块,......
  • redis:redis-cli指令
    学习自:redis-cli命令详解-小学弟--博客园1、登录:redis-cli[选项]选项选项默认值说明对应配置项redis.conf-h<hostname>127.0.0.1以哪个主机名/IP登录Redis如果某个IP没在conf文件中绑定,那就不能用它登录bind-p<port>6379服务器端口号por......
  • redis:set与zset
    学习自:Redis的五种基本数据类型_redis的五种数据类型_喵先森爱吃鱼的博客-CSDN博客Set集合,存放一系列无重复元素 常用命令命令用法说明scardscardKK中元素个数saddsaddKV1V2V3V4往K中添加数据sremsremKV从K中移除数据sismember......
  • redis:List
    List与Java中的LinkedList类似,可以看做一个双向链表,同时支持正反向检索。特征:有序元素可重复增删速度快查询速度一般常用命令命令用法说明lpushrpushlpush/rpushKV1V2V3往K的左/右插入Vlpoprpoplpop/rpopK从K的左/右移除一个Vllenl......