C#中如何使用redis

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));
//删除
_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的资料请关注呐喊教程其它相关文章!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。