進一步學習 redis

注意:當出現 redis 連接超時時 如下執行:

1、springboot 項目使用 redis

使用 spring 自帶的 :

@Autowired
private RedisTemplate redisTemplate;

如果再類中 無法發現 redisTemplate bean 的話,在main 啓動類中加如下:

@Autowired
private RestTemplateBuilder builder;

// 使用RestTemplateBuilder來實例化RestTemplate對象,spring默認已經注入了RestTemplateBuilder實例
@Bean
public RestTemplate restTemplate() {
    return builder.build();
}

 

在使用redis 的時候要遵守一定的規範,可參考如下文檔:

https://blog.fundebug.com/2018/09/21/redis_incident/

 

2、用 scan 替代 keys 

@Autowired
RedisTemplate<String, Object> redisTemplateObject;
/** * 以count爲步長查找符合pattern條件的keys * * @param redisTemplate 指定redis * @param pattern 匹配條件 * @param count 一次在count條記錄中match符合pattern條件的記錄。若count<=0,使用1000 * @return Set<String> 若limit<= 0,返回所有;否則返回查找結果 */
public Set<String> scanKeys(String pattern, int count) {
    return redisTemplateObject.execute(new RedisCallback<Set<String>>() {
        @Override
        public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
            Set<String> tmpKeys = new HashSet<>();
            ScanOptions options;
            if (count <= 0) {
                options = ScanOptions.scanOptions().match(pattern).count(1000).build();
            } else {
                options = ScanOptions.scanOptions().match(pattern).count(count).build();
            }
            // 迭代一直查找,直到找到redis中所有滿足條件的key爲止(cursor變爲0爲止)
            Cursor<byte[]> cursor = connection.scan(options);
            while (cursor.hasNext()) {
                tmpKeys.add(new String(cursor.next()));
            }
            return tmpKeys;
        }
    });
}

參考:https://horizonliu.github.io/2019/07/25/Redis%E7%94%A8scan%E4%BB%A3%E6%9B%BFkeys/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章