不会一次全部进行扫描, 减少服务器阻塞 Set<String> tokenKeySet = stringRedisTemplate.execute((RedisCallback<Set<String>>) connection -> { Set<String> keysTmp = new HashSet<>(); try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder() .match(CacheConstants.LOGIN_TOKEN_KEY + "*") // 对应key .count(1000).build())) { // 设置count 扫描范围 while (cursor.hasNext()) { keysTmp.add(new String(cursor.next(), StandardCharsets.UTF_8)); } } catch (Exception e) { log.error("获取所有的在线用户key报错", e); } return keysTmp; });
// 业务代码分批次获取
List<List<String>> tokenKey2List = CollUtil.split(tokenKeySet, 10); for (List<String> tokenKeyList : tokenKey2List) { List<LoginUser> loginUserList = redisOldCache.redisTemplate.opsForValue().multiGet(tokenKeyList); if (CollUtil.isEmpty(loginUserList)) { continue; }