Redis key to delete the same prefix

      How gracefully delete Redis set the set the same prefix key?
      There Redis command to delete a single data DEL, but there is no mass delete a specific prefix key commands, but we often encounter the need to remove the prefix according to the business scene, then how on earth do? You may pass after a search will get the answer below:
redis-cli --raw keys "prefix-*" | xargs redis-cli del

        Linux directly in the match by redis command of keys to all the key, and then call the system command xargs to delete, seemingly perfect, but in reality a huge risk. This is a bomb ready to explode! We all know that Redis service is single-threaded mode, use the command keys * key when the query can block the normal service request, redis even result in downtime, so certainly not. Therefore, we should avoid in a production environment using the method on top of that what an elegant way to solve it? SCAN!

SCAN Introduction

       Redis from 2.8 version began to support SCAN command, which is a cursor-based iterator is invoked after each returns a new cursor, the next time the user needs to use this new iteration cursor cursor parameters as SCAN command, in order to continuation of the previous iteration, until the server returns a cursor value of 0, a complete traversal process is over.
       SCAN basic syntax of the command is as follows:
 
scan cursor [MATCH pattern] [COUNT count]

The MATCH : matching rules, e.g. traversed to all key beginning ops-coffee- be written ops-coffee- *, can be written as the intermediate containing -coffee- * -coffee- * cursor: the cursor,

COUNT : COUNT action option is to allow users to inform iteration command should return the number of elements from the data set at each iteration, COUNT just a hint of incremental iteration of command and do not represent the number of real return, for example, you 2 is provided with a COUNT may return to three elements, but elements of the data will be returned positively correlated with COUNT setting, the default value of COUNT is 10.
     The operation keys in jedis the scan and to remove the key with the same prefix .
 
public  void testSetDel (Jedis jedis) {
         the try { 
            log.info ( "the begin Tests ---------------- ----------------- " ); 
            initRedisData (jedis); 
            String givenKey =" prefix_ * " ; 
            delValuesByKeys (givenKey, jedis); 
 
            log.info ( " start using the scan data to delete ------------ " ); 
            initRedisData ( jedis); 
            the this .delSetValues (givenKey, jedis); 
 
            the Set <String> Keys = jedis.keys (givenKey); 
            log.info ( "End ---------------- Tests - --------------- whether there is a key result of the same prefix = "+!CollectionUtils.isEmpty (Keys)); 
        } the catch (Exception E) { 
            log.error ( "delete the specified prefix key corresponding to the key" + E); 
        } the finally {
             IF ! (Jedis = null ) { 
                jedis.close ( ); 
                log.info ( "Close jedis connection" ); 
            } 
        } 
    } 
    / ** 
     * Java Redis delete key corresponding to the key value of the specified prefix 
     * @param givenKey 
     * @return 
     * / 
    public Boolean delSetValues (String givenKey, jedis jedis ) throws  Exception {
        log.info ("Began to blur in the data set to delete, givenKey =" + givenKey); 
        List <String> Keys = getByScan (givenKey, jedis); 
        log.info ( "to be deleted key is" + Keys); 
        String [] Array = Keys .toArray ( new new String [0 ]); 
        jedis.del (Array); 
        return  to true ; 
    } 
    / ** 
     * Jedis delete key corresponding to the specified prefix key, using Keys 
     * @param givenKey 
     * @return 
     * / 
    public Boolean delValuesByKeys ( givenKey String, jedis jedis) throws Exception { 
        log.info ( "start of fuzzy set data deletion, givenKey =" + givenKey); 
        the Set <String> Keys = jedis.keys (givenKey);
         for (String key: Keys) { 
            log.info ( "current key is:" + key) ; 
            jedis.del (Key); 
        } 
        return  to true ; 
    } 
   Private  void initRedisData (jedis jedis) { 
        jedis.set ( "prefix_1333", ". 1" ); 
        jedis.set ( "prefix_2KKKKK", "2" ); 
        jedis.set ( "prefix_3 ha ha ha ha ha ha", "777" );
    }    // 使用 scan
    
 
public List<String> getByScan(String key, Jedis jedis) { List<String> list = new ArrayList<>(); ScanParams params = new ScanParams(); params.match(key); params.count(100); String cursor = "0"; while (true) { ScanResult scanResult = jedis.scan(cursor, params); List<String> eles = scanResult.getResult(); if (!CollectionUtils.isEmpty(eles)) { list.addAll(eles); } Cursor =scanResult.getStringCursor (); IF ( "0" .equals (Cursor)) { BREAK ; } } log.info ( "data set is found getByScan ============" + List) ; return List; }

      Test Results:

---------------- Tests begin -----------------
开始模糊删除set中的数据,givenKey = prefix_*
当前 key 是 :prefix_1333
当前 key 是 :prefix_3哈哈哈哈哈哈
当前 key 是 :prefix_2KKKKK
开始使用 scan 删除数据 ------------
开始模糊删除set中的数据,givenKey = prefix_*
getByScan 查到的数据集是 ============ [prefix_1333, prefix_2KKKKK, prefix_3哈哈哈哈哈哈]
即将删除的key是 [prefix_1333, prefix_2KKKKK, prefix_3哈哈哈哈哈哈]
---------------- Tests end ----------------- 是否存在相同前缀的 key result = false    

 

   总结:虽然不提倡使用keys命令删除key,但是,本文示例依然给出了示例,目的在于了解使用原理。当然,比使用scan命令删除key效果更好的方案是直接调用Lua脚本,童鞋们自己琢磨吧!
 

Guess you like

Origin www.cnblogs.com/east7/p/11665392.html