jetcache 请问如何在已知cache实例的情况下,获取到这个cache实例的cacheName

ao218c7q  于 22天前  发布在  其他
关注(0)|答案(2)|浏览(19)

我自己定义了一个redis工具类,比如调用redis scan命令进行批量获取key的。这时候就得把cachename传过来做key前缀,但是我删除的时候,又想调用jetcache的REMOVE_ALL接口,所以又把cache实例传过来了,这样的情况下,我的cache和cacheName就传了两次,为了避免其他人在调用我这个工具类的时候,传的cacheName入参和cache实例对应的cacheName不一致,我想从cache实例直接拿到name,但是我看了一下源码,好像最顶层的 cachecache.config() 都没法获取到cacheName。请问如何才能正确拿到cacheName
下面是我定义的工具类方法

private static void removeAllByRedis(Cache cache, String cacheName, String pattern) {
    // 这里入参的cacheName,如何从cache中直接获取到
    try {
        RedisClusterCommands commands = getLettuceCommands(cache);

        KeyScanCursor<byte[]> scanCursor = new KeyScanCursor<>();
        scanCursor.setCursor("0");
        scanCursor.setFinished(false);

        ScanArgs scanArgs = new ScanArgs();
        scanArgs.match(cacheName + pattern);
        scanArgs.limit(10);
        String cursor;

        do {
            //使用scan命令获取数据,使用cursor游标记录位置,下次循环使用
            assert commands != null;
            scanCursor = commands.scan(scanCursor, scanArgs);
            // 返回0 说明遍历完成
            cursor = scanCursor.getCursor();
            List<byte[]> list = scanCursor.getKeys();
            if (CollUtil.isNotEmpty(list)) {
                HashSet<String> keySet = new HashSet<>();
                for (byte[] bytes : list) {
                    keySet.add(new String(bytes).replaceFirst(cacheName, ""));
                }
                // 调用jetCache接口删除
                cache.REMOVE_ALL(new HashSet<>(keySet));
            }
            scanCursor.setCursor(cursor);
        } while (!"0".equals(cursor));
    } catch (Exception e) {
        log.error("扫描cacheName:" + cacheName + ",pattern:" + pattern + "失败", e);
    }
  }
xu3bshqb

xu3bshqb1#

按现在的设计,Cache实例本身是没有name这个属性的,它也不知道自己的name。出于上层代码的管理需要,才会给它起个名字,这个名字也在上层代码维护。

所以光有Cache是得不到name的,你得自己想办法。

dkqlctbz

dkqlctbz2#

非常感谢您的回复。

相关问题