如何实现Guava缓存来存储和获取不同类型的对象?

时间:2018-11-07 12:30:20

标签: java generics caching design-patterns guava

现在,我的缓存如下所示:

public class TestCache {

    private LoadingCache<String, List<ObjectABC>> cache;

    TestCache() {
        cache = CacheBuilder.newBuilder().expireAfterAccess(10, TimeUnit.MINUTES).maximumSize(25)
                .build(new CacheLoader<String, List<ObjectABC>>(
                ) {
                    @Override
                    public List<ObjectABC> load(String key) throws Exception {
                        // TODO Auto-generated method stub
                        return addCache(key);
                    }

                });
    }

    private List<ObjectABC> addCache(String key) {
    final JoiObjectMapper mapper = new JoiObjectMapper();

        final Collection<File> allConfigFiles = FileUtils.listFiles(new File(key), null, true);
        final List<ObjectABC> configsList = new ArrayList<>();

        allConfigFiles.forEach(configFile -> {
            try {
                     configsList.add(mapper.readValue(configFile, new TypeReference<ObjectABC>() {
                      }));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        return configsList;
    }

    public List<ObjectABC> getEntry(String key) {
         try {
            return cache.get(key);
        } catch (ExecutionException e) {
            throw new NonRetriableException(String.format(
                    "Exception occured while trying to get data from cache for the key : {} Exception: {}",
                    key.toString(), e));
        }
    }
}

在上面的代码中,当我传递String key(这是本地文件夹的路径)时,它将获取该位置中存在的所有文件,并使用ObjectABC将它们映射到ObjectMapper

现在我的问题是我想改为拥有一个通用的加载缓存,例如
LoadingCache<String, List<Object>>

我想将不同文件夹中的文件映射到不同的对象,例如将 / root / Desktop / folder1 中的文件映射到List<ObjectABC>并将 / root / Desktop / folder2 中的文件映射到List<ObjectDEF>并能够存储并从缓存中检索该信息。

如何将用于映射的对象的信息传递给缓存?

1 个答案:

答案 0 :(得分:1)

您可以创建一个包装LoadingCache<Key<?>, Object>的自定义类,如下所示:

class HeterogeneousCache {

    private final LoadingCache<Key<?>, Object> cache;

    public <T> T get(Key<T> key) throws ExecutionException {
        return key.getType().cast(cache.get(key));
    }
}

@Value // provides constructor, getters, equals, hashCode
class Key<T> {

    private final String identifier;
    private final Class<T> type;
}

(为简单起见,我使用了Lombok的@Value注释)

当然,这只是一个存根,您可能需要根据需要对其进行调整。主要问题可能是您无法获得Class<List<ObjectABC>>-您只能获得Class<List>。最简单的方法是将List<ObjectABC>包装为某些自定义类型。较困难的方法(不建议使用)是使用番石榴的TypeToken


归因:此答案基于Frank Appel的标题为How to Map Distinct Value Types Using Java Generics的帖子,该帖子本身基于Joshua Blochtypesafe hetereogeneous containers 有效的Java


编辑:完整的解决方案

由于OP想要List<T>作为结果,并且由于他需要TypeReference<T>的实例,因此我在Class<T>中用TypeReference<T>替换了Key<T>

@Value // provides constructor, getters, equals, hashCode
class Key<T> {
    private final String identifier;
    private final TypeReference<T> typeReference;
}

CustomHeterogeneousCache的外观如下:

class CustomHeterogeneousCache {

    private final LoadingCache<Key<?>, List<?>> cache = CacheBuilder.newBuilder()
            .expireAfterAccess(10, TimeUnit.MINUTES)
            .maximumSize(25)
            .build(CacheLoader.from(this::computeEntry));

    @SuppressWarnings("unchecked")
    public <T> List<T> getEntry(Key<T> key) {
        return (List<T>) cache.getUnchecked(key);
    }

    private <T> List<T> computeEntry(Key<T> key) {
        final JoiObjectMapper mapper = new JoiObjectMapper();
        final Collection<File> allConfigFiles = FileUtils.listFiles(new File(key.getIdentifier()), null, true);
        return allConfigFiles.stream()
                .map(configFile -> {
                    try {
                        return mapper.readValue(configFile, key.getTypeReference());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                })
                .collect(Collectors.toList());
    }
}

由于TypeReference的实现不具有值语义,因此用户必须确保每个Key均创建一次,然后仅被引用,例如:

class Keys {
    public static final Key<ObjectABC> ABC = new Key<>("/root/Desktop/folder1", new TypeReference<ObjectABC>() {
    });
    public static final Key<ObjectDEF> DEF = new Key<>("/root/Desktop/folder2", new TypeReference<ObjectDEF>() {
    });
}