• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C#中如何使用redis

c# 搞代码 4年前 (2022-01-09) 13次浏览 已收录 0个评论

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

3、常用操作

IDatabase _cacheClient = RedisHelper.GetDataBase(4);
//key是否存在
_cacheClient.KeyExists("key")
//设置key-vaule
_cacheClient.StringSet("key", "value");
//设置过期时间
_cacheClient.KeyExpire("key", TimeSpan.FromMinutes(1));<b>本文来源gao@dai!ma.com搞$代^码!网7</b>
//删除
_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)

以上就是C#中如何使用redis的详细内容,更多关于C#使用redis的资料请关注搞代码其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C#中如何使用redis

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址