SpringBoot中使用Redis的keys替代方案scan


眾所周知redis的keys命 在測試環境這樣開發沒有問題, 由於項目對redis依賴比較大, 就網上找了一些關於redis的keys命令, 得知keys命令執行的時候會嚴重阻塞線上其它命令的正常請求, 於是做了以下替代方案

/**
     *  獲取指定前綴的一系列key
     *  使用scan命令代替keys, Redis是單線程處理,keys命令在KEY數量較多時,
     *  操作效率極低【時間復雜度為O(N)】,該命令一旦執行會嚴重阻塞線上其它命令的正常請求
     * @param keyPrefix
     * @return
     */
    public Set<String> keys(String keyPrefix) {
        String realKey = "*" + keyPrefix + "*";
        try {
            return redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
                Set<String> binaryKeys = new HashSet<>();
                Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(realKey).count(Integer.MAX_VALUE).build());
                while (cursor.hasNext()) {
                    binaryKeys.add(new String(cursor.next()));
                }
                return binaryKeys;
            });
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  刪除指定前綴的一系列key
     * @param keyPrefix
     */
    public void removeAll(String keyPrefix) {
        try {
            Set<String> keys = keys(keyPrefix);
            redisTemplate.delete(keys);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

 


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM