Using Redis as Cache and C# client

拈花ヽ惹草 提交于 2019-12-10 21:10:23

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/33309825/using-redis-as-cache-and-c-sharp-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!