In the previous article, Why does Redis block when deleting a large key? It is said that the del command should not be called directly to delete the key, which can easily cause the request to be blocked. How should it be handled?
This time, let’s give an example from the perspective of code writing.
In Redis, there are several special structures, String, List, Hash, Set, ZSet. Why does it block when deleting large keys from Redis? It can be seen that you cannot directly del (except string), but should use the scan method, and each type also has its own scan method. Next, take Java Jedis as an example.
List
String key = "demo"; int length = ("demo"); if (length > 1024) { int size = 100; int count = 0; do { //The first 100 are processed at each time // Redis will also determine whether the currently passed index exceeds the current list length // See ltrimCommand (key, 0, size); count += size; } while (count < length); } (key);
Set
String key = "demo"; long length = (key); if (length > 1024) { //100 traversals each time ScanParams scanParams = new ScanParams().count(100); // The passed cursor cursor = "0"; ScanResult<String> sscan; do { //Pass the scan parameter sscan = (key, cursor, scanParams); if (!(())) { // traversal and delete the result in sequence ().stream().forEach(member -> { (key, member); }); } // Pass in the cursor you will be traversed next time cursor = (); } while (!()); } (key);
ZSet
String key = "demo"; // Get the length of zsetlong length = (key); if (length > 1024) { int size = SIZE; int count = 0; do { // Delete the specified collection (key, 0, size); count += size; } while (count < length); } (key);
Hash
String key = "demo"; // Get the number of fields in Hashlong length = (key); if (length > THROLD) { ScanParams scanParams = new ScanParams(); // traversal size (SIZE); // Which fields are matched ("*"); ScanResult<<String, String>> result; cursor = "0"; do { // traverse fields result = (key, cursor, scanParams); if (!(())) { // Delete the specified field ().stream().forEach(x -> { (key, ()); }); } cursor = (); } while (!()); } (key);
This is the end of this article about several ways to delete Redis big keys. For more related content to delete Redis big keys, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!