进一步学习 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/

发布了20 篇原创文章 · 获赞 0 · 访问量 9174

猜你喜欢

转载自blog.csdn.net/qq_30346433/article/details/103819849