Redis LOST data?
這邊討論數據丟失的幾個可能原因。
鍵值被刪除或找不到的幾個可能原因?
1) key 可能因為 TTL 到期,而造成 Key Expired 被刪除。
2) key 可能因為 redis 的內存使用量,達至 maxmemory 的限制而被移除。
3) 某些程序將 key 進行了 delete。
> del key
4) 數據被清空的原因,通常您的前端應用有執行了 flushall 或者是 flushdb 命令,導致您的數據被刪除。
> flushall
> flushdb[+] Redis - flushall :
https://redis.io/commands/FLUSHALL
-
Delete all the keys of all the existing databases, not just the currently selected one. This command never fails.
- [+] Redis - flushdb :
https://redis.io/commands/flushdb
-
Delete all the keys of the currently selected DB. This command never fails.
-
5) 客戶存資料在 database1,但卻到 database0去找數據。
> info Keyspace
# Keyspace
db0:keys=4,expires=1,avg_ttl=597654
db1:keys=3,expires=0,avg_ttl=0 <------
6) 發生主從切換,而原從節點來不及完整同步(Replication)數據,造成缺少少部份數據。
Q: 如何監控?
A: 透過使用 Redis keyspace notifications 來監控。
可以透過”實施 Redis 密鑰空間通知”,來監控命令執行的狀況,進一步來確認您鍵值被刪除的原因及時間點,以下文檔,提供您參考。
[+] How do I implement Redis keyspace notifications in ElastiCache?
https://aws.amazon.com/premiumsupport/knowledge-center/elasticache-redis-keyspace-notifications/
[+] 如何在 ElastiCache 中實施 Redis 密鑰空間通知?
https://aws.amazon.com/cn/premiumsupport/knowledge-center/elasticache-redis-keyspace-notifications/?nc1=h_ls
借助 Redis 密鑰空間通知,您可以訂閱 PubSub 頻道。 Redis 命令或數據發生更改時,客戶端會通過該頻道接收已發布的事件。當應用程序必須對存儲在一個或多個特定鍵中的值發生的更改做出反應時,這些通知會很有幫助。您還可以使用 Redis 密鑰空間通知跟踪數據集的更改。密鑰空間通知功能在版本 2.8.6 和更高版本中可用。
測試方法,先去調整參數組後的設定。
$ ./redis-cli -h xxx -p 6379
> SET key1 value1 ex 5$ ./redis-cli -h xxx -p 6379 --csv psubscribe '*'
Reading messages... (press Ctrl-C to quit)
"psubscribe","*",1
"pmessage","*","__keyspace@0__:key1","set"### Generate and monitor events using Redis-py ###
# cat subscribe.py
# cat createkey.py
# python2 subscribe.py### 重啓(reboot)了該redis節點來模擬連接中斷的情形. 原本的 Pub/Sub 的訂閱在此時中斷並收到如下的訊息。 ###Error: Server closed the connection
Q: 如何避免使用者誤用 flushdb、flushall 命令?
可以透過使用 ElatiCache Redis 中的參數 rename-commands,來變更這幾個命令的名稱,以避免使用者誤用。
[+] Redis-specific parameters — Redis 5.0.3 parameter changes:
Ccalled rename-commands, that allows you to rename commands to user specified names and prevent accidental use of potentially intrusive or expensive commands. Amazon ElastiCache for Redis ensures that the command name changes are propagated to all nodes in the cluster immediately in an online manner and without the need for manual intervention. Furthermore, the command name changes persist through node reboots and replacements, thereby providing a fully-managed experience.