asp.net.net-coreredisstackexchange.redis

How to get expiration time for a key on Redis using Dotnet Core?


I'm following this example to implement Redis cache on Dotnet Core.

Unfortunately t seems that both Get(key) and GetString(key) only return the value, not the metadata such as expiry.

When I use redis-cli I'm able to retrieve both the data and metadata using HGETALL key

1) "absexp"
2) "637153531959962660"
3) "data"
4) "[{<snip>}]"
5) "sldexp"
6) "-1"

Is there any way to access this metadata from my code?

There might of course be workarounds like adding the expiry in the data object itself or adding a second key that contains the metadata, but neither solutions are very elegant.


Solution

  • Assuming you are using Microsoft.Extensions.Caching.StackExchangeRedis.

    There is no way to get this from reviewing the docs and source.

    You will have to get it using StackExchange.Redis directly.

    Follow the same approach used on RedisCache.cs:

    //RedisCacheOptions options as passed to RedisCache contructor.
    ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(options.ConfigurationOptions);
    IDatabase cache = connection.GetDatabase();
    HashEntry[] results = cache.HashGetAll(key);