mercredi 7 novembre 2018

How to implement Guava cache when I plan to store and get different types of objects in the cache?

Right now by code looks like the following:

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));
    }
}

}

In the above code, when I pass a String 'key' (which is path to a local folder), it takes all the files present in the location and maps all the files to ObjectABC using ObjectMapper.

Now my problem is that I want to instead have a generic loading cache like : LoadingCache<String, List<Object>>

And I want to map files in different folders to different Objects , (like say : map files in /root/Desktop/folder1 to List<ObjectABC> and map files in /root/Desktop/folder2 to List<ObjectDEF>) and be able to store and retrieve that information from the cache.

I want to understand what should be the best way to pass the information of which object to use for mapping to the cache

Aucun commentaire:

Enregistrer un commentaire