1. 程式人生 > 程式設計 >C#中如何使用redis

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

C#中如何使用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的資料請關注我們其它相關文章!