Azure Cache - How to Determine if a Key is in cache?
Asked Answered
S

1

6

Is there a way, using Azure Caching, to determine if an object having a specific key exists in cache, without actually returning the object itself?

I'm currently doing something like

    public bool IsKeyInCache(string cacheKey)
    {
        DataCacheItem item = null;
        CacheRetryPolicy.ExecuteAction(() =>
        {
            item = cache.GetCacheItem(cacheKey);
        });

        return item != null;
    }

But, because the object in cache is very large and expensive to deserialize, performance is horrible.

I've dug through the MSDN documentation and don't see any alternative, but maybe I'm missing something.

My best idea so far is to add a small "marker" object to cache at the same time as my large object and check for existence of the "marker" object where deserialization is inexpensive. But this isn't a robust solution, as it's entirely possible for my large object to get purged from cache while the "marker" object remains.

Supat answered 22/11, 2013 at 21:59 Comment(2)
I'll take a quick stab at why it might not be implemented for any cache in particular ... simply because of a race condition. Between checking to see whether the key exists and reading the value of the key, the item might be evicted from the cache.Buzz
Q: Why don't you just ask for the value? Just curious - what's the use case for checking whether or not the key happens to be in cache?Enterovirus
E
0

I believe the API you're looking for is DataCache.Get(key):

But I still think you're best bet is to NOT "micro-manage" the cache, just query, and let Azure decide.

IMHO...

Enterovirus answered 24/11, 2013 at 7:8 Comment(3)
DataCache.Get() returns the item if it is in cache. All I want is a yes/no answer as to whether the specified key is in the cache.Supat
And if it isn't in cache, it returns a NULL. DataCache.Get(key) is honestly your best choice, even for a boolean yes/no. IMHO...Enterovirus
It's my "best choice" because it's my only choice, apparently. Suppose I've cached a very large object. Why pay the price to transfer it out of cache (which may be on a different member of the cluster) and across the network to my role instance, when all I want to know is "does this key exist?"Supat

© 2022 - 2024 — McMap. All rights reserved.