最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#中如何使用redis

 更新時間:2020年07月06日 15:54:34   作者:邱@cnblogs  
這篇文章主要介紹了C#中如何使用redis,文中示例代碼非常詳細,幫助大家更好的理解和學習,感興趣的朋友可以了解下

redis 是一個非關(guān)系型高性能的key-value數(shù)據(jù)庫。和Memcached類似,它支持存儲的value類型相對更多,包括string(字符串)、list(鏈表)、set(集合)、zset(sorted set --有序集合)和hash(哈希類型)。這些數(shù)據(jù)類型都支持push/pop、add/remove及取交集并集和差集及更豐富的操作,而且這些操作都是原子性的。在此基礎(chǔ)上,redis支持各種不同方式的排序。與memcached一樣,為了保證效率,數(shù)據(jù)都是緩存在內(nèi)存中。區(qū)別的是redis會周期性的把更新的數(shù)據(jù)寫入磁盤或者把修改操作寫入追加的記錄文件,并且在此基礎(chǔ)上實現(xiàn)了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")
//設(shè)置key-vaule
_cacheClient.StringSet("key", "value");
//設(shè)置過期時間
_cacheClient.KeyExpire("key", TimeSpan.FromMinutes(1));
//刪除
_cacheClient.KeyDelete("key");

4、redis 雖然也可以做消息隊列,實現(xiàn)也簡單,但弊端同樣明顯,不推薦

//發(fā)布
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、計數(shù)器,用于秒殺、搶購控庫存

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

//判斷,比如和緩存里的商品總庫存比較

//計數(shù)增加
_cacheClient.StringIncrement("key", 2)

以上就是C#中如何使用redis的詳細內(nèi)容,更多關(guān)于C#使用redis的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

双辽市| 大庆市| 江都市| 明水县| 潜江市| 保亭| 丹江口市| 新蔡县| 永仁县| 尼勒克县| 依安县| 忻城县| 新和县| 方山县| 宁波市| 南阳市| 卢氏县| 营口市| 铁岭市| 上栗县| 东平县| 瑞金市| 政和县| 芜湖市| 东丰县| 毕节市| 固镇县| 弥渡县| 苏尼特右旗| 通化县| 吴川市| 十堰市| 中宁县| 尉犁县| 卢湾区| 深水埗区| 长武县| 西峡县| 玛沁县| 信阳市| 长海县|