Search code examples
redisservicestack.redis

Using Redis as Cache and C# client


I'm new to Redis and trying to figure out a simple way to use Redis as a local cache for my C# app. I've downloaded and ran the redis-server from https://github.com/MSOpenTech/redis/releases

I can successfully store a key value and retrieve it as follows:

        var redisManager = new PooledRedisClientManager("localhost:6379");
        using (var redis = redisManager.GetClient())
        {
            redis.Set("mykey_1", 15, TimeSpan.FromSeconds(3600));
            // get typed value from cache
            int valueFromCache = redis.Get<int>("mykey_1"); // must be = 
        }

I want to limit the amount of memory Redis uses on my server and I also want redis to automatically purge values when memory fills. I tried the maxmemory command but in the redus-cli program maxmemory is not found.

Will Redus automatically purge old values for me? (I assume not) and if not, is there a way that I can make the default behavior of redis do that with the Set method I'm using below?

If I'm heading down the wrong path, please let me know.


Solution

  • The answer to your question is described here: What does Redis do when it runs out of memory?

    Basically, you set the maxmemory from the config file, and not from the redis-cli. You can also specify a maxmemory-policy, which is a set of procedures that redis executes when it runs out of the specified memory. According to that config file, there are a total of 6 policies that Redis is using when it runs out of memory:

    volatile-lru -> remove the key with an expire set using an LRU algorithm

    allkeys-lru -> remove any key according to the LRU algorithm

    volatile-random -> remove a random key with an expire set

    allkeys-random -> remove a random key, any key

    volatile-ttl -> remove the key with the nearest expire time (minor TTL)

    noeviction -> don't expire at all, just return an error on write operations

    You can set those behaviours using the maxmemory-policy directive that you find in the LIMITS section of redis.conf file (above the maxmemory directive).

    So, you can set an expire time to every key that you store in Redis (a large expire time) and also set a volatile-ttl policy. In that way, when Redis runs out of memory, the key with the smallest TTL (which is also the oldest one) is removed, according to the policy that you've set.