redis在C#中的使用

redis 是一个非关系型高性能的key-value数据库。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

下面介绍下,在C#中如何使用redis

1、引用 StackExchange.Redis

 2、redis 工具类

    public class RedisHelper
    {
        private static ConnectionMultiplexer multiplexer { get; set; }
        static RedisHelper()
        {
        }

        public static IDatabase GetDataBase(int dbNums = 1)
        {
            if (multiplexer == null)
                Init();
            return multiplexer.GetDatabase(dbNums);
        }

        public static ConnectionMultiplexer GetMultiplexer()
        {
            if (multiplexer == null)
                Init();

            return multiplexer;
        }
        public static bool IsConnect(string key, IDatabase redisDb, string module, string action)
        {
            if (!redisDb.IsConnected(key))
            {
                LogHelper.Error("current redis is not connect", null, module, action);
                return false;
            }
            return true;
        }

        private static void Init()
        {
            try
            {
                var configString = ConfigurationManager.AppSettings["RedisConfigString"];
                ConfigurationOptions options = ConfigurationOptions.Parse(configString);
                multiplexer = ConnectionMultiplexer.Connect(options);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "RedisHelper", "Static");
            }
        }
    }
View Code

3、常用操作

IDatabase _cacheClient = RedisHelper.GetDataBase(4);
//key是否存在
_cacheClient.KeyExists("key")
//设置key-vaule
_cacheClient.StringSet("key", "value");
//设置过期时间
_cacheClient.KeyExpire("key", TimeSpan.FromMinutes(1));
//删除
_cacheClient.KeyDelete("key");

4、redis 虽然也可以做消息队列,实现也简单,但弊端同样明显,不推荐

//发布
ConnectionMultiplexer multiplexer = RedisHelper.GetMultiplexer();
ISubscriber sub = multiplexer.GetSubscriber();
var queue = sub.Publish("channel name", "message");

//订阅
ConnectionMultiplexer multiplexer = RedisHelper.GetMultiplexer();
ISubscriber sub = multiplexer.GetSubscriber();
sub.Subscribe("channel name", (channel, message) =>
{
    //TODO
});

 5、计数器,用于秒杀、抢购控库存

//取值,不存在则初始为0
long num = _cacheClient.StringIncrement("key", 0)

//判断,比如和缓存里的商品总库存比较

//计数增加
_cacheClient.StringIncrement("key", 2)
原文地址:https://www.cnblogs.com/qiujz/p/13207807.html