C # use Redis simple storage

Redis is an open source use ANSI C language support network, it can also be based on memory persistence journaling, Key-Value database.

They used it to store cached data, can very easily achieve the cache expires refresh mechanism.

Redis languages ​​can connect to the database server, this article will recommend a very simple C # connection Redis database of open source projects.

General recommendations

Usually, C # will use Redis recommended way to add NuGet package StackExchange.Redis to use.

When using the code form as follows:

ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,password=CeshiPassword");
IDatabase db = redis.GetDatabase();
string value = "name";
db.StringSet("mykey", value);
Console.WriteLine(db.StringGet("mykey"));

Personally I think its use is not intuitive.
This name is not as ConnectionMultiplexer can guess, can not remember it or even see it have anything to do with Redis. Then, from the most simple to use point of view, it requires the user to understand the concept of inside Database.

Recommend a concise version csredis

Project Address: https://github.com/ctstone/csredis

Its name to earth, easy to use, in the form as follows.

using (var redis = new RedisClient("localhost"))
{
   redis.Auth("password");
   redis.Set("mykey", "name", 25);  // 有效期25秒
   Console.WriteLine(redis.Get("mykey"));
} 

A simple helper class

When here concerned only with the simple package, so that the use of keys and values, and its length is valid, such as, Common token buffer to meet the scene.

public class RedisHelper
{
    private static RedisClient _RedisCli;
    private static RedisClient RedisCli
    {
        get
        {
            if (_RedisCli == null)
            {
                _RedisCli = new RedisClient("192.168.0.100");
                _RedisCli.Auth("redispassword");
            }
            return _RedisCli;
        }
    }

    /// <summary>
    /// 取得缓存值
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetKey(string key)
    {
        return RedisCli.Get(key);
    }

    /// <summary>
    /// 保存值并设置有效期(second)
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="expireSeconds"></param>
    public static void SetKey(String key, String value, int expireSeconds)
    {
        RedisCli.Set(key, value, expireSeconds);
    }
}

Guess you like

Origin www.cnblogs.com/timeddd/p/11117787.html