码迷,mamicode.com
首页 > Windows程序 > 详细

redis在C#中的使用

时间:2020-06-29 15:07:27      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:支持   multiple   而且   消息   false   包括   使用   ror   并且   

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");

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
});

 

redis在C#中的使用

标签:支持   multiple   而且   消息   false   包括   使用   ror   并且   

原文地址:https://www.cnblogs.com/qiujz/p/13207807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!