ZiggyCreatures / FusionCache

FusionCache is an easy to use, fast and robust hybrid cache with advanced resiliency features.
MIT License
1.65k stars 87 forks source link

[QUESTION] Can you tell if the cache hit comes from Memory or Distributed? #194

Closed JarrodOsborne closed 6 months ago

JarrodOsborne commented 7 months ago

I have a multi-layer FusionCache set up (in-memory & Redis).

My issue is that objects retrieved from the memory store need to be immutable, so I will likely have to clone them upon retrieval. However I don't want to clone if the hit comes from Redis as that would be pointless. Is there a way to determine if the cache item retrieved came from in-memory or distributed?

jodydonetti commented 7 months ago

Hi @JarrodOsborne and thanks for using FusionCache!

Currently there's no way to know that when getting a value, but let me ask how are you approaching the cloning itself? Maybe I can think of something, you are not the first one to think about wanting to clone objects you got back from the cache.

jodydonetti commented 6 months ago

Closing as there has not been a response.

JarrodOsborne commented 6 months ago

Hi @jodydonetti I ended up writing a wrapper around IMemoryCache which does a clone,

public bool TryGetValue(object key, out object value)
{
    var exists = _memoryCache.TryGetValue(key, out object innerValue);
    value = innerValue?.Clone();
    return exists;
}

and providing this version of IMemoryCache to FusionCache.

The clone is just a JSON copy

public static T Clone<T>(this T source) where T : class
{
    return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source, _settings), _settings);
}
jodydonetti commented 6 months ago

Hi @JarrodOsborne , oooh that is smart, I haven't thought about it!

Glad it worked out in the end.

JarrodOsborne commented 6 months ago

@jodydonetti Going back to the original question, would this feature be considered in the future? I understand it's a little niche, but now I'm at the stage where I'm logging the duration of my cache operations and it would be nice to know what layer I'm hitting. Unless there's another way to achieve this that I don't know about?

jodydonetti commented 6 months ago

Hi @JarrodOsborne , I'm not planning it right now, but I'm still thinking about how it could be made without a major change in the api surface area.

Do you have any hints or ideas you'd like to share?

jodydonetti commented 1 month ago

Hi all, Auto-Cloning is coming in v1.3.0 which will be out... I think later today 😬

Will update later.

jodydonetti commented 1 month ago

Hi all, v1.3.0 is out 🥳