使用redis

通过 Nuget获取包StackExchange.Redis

写数据:

  ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,password=CeshiPassword1");
   IDatabase db = redis.GetDatabase();
   db.StringSet("name", "我的名称", TimeSpan.FromSeconds(10));   //10s过期,也可不写

写数据:

  ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,password=CeshiPassword1");
  IDatabase db = redis.GetDatabase();
 string str=  db.StringGet("name");   // key不存在时返回null
        db.KeyExpire("name", TimeSpan.FromSeconds(10));  //读操作不会对数据延时,此句重新延时10s,不是增加10s
            if (str == null)
                this.textBox1.Text = "null";
            else
                this.textBox1.Text = str;

查看还有多时生存时间:

 TimeSpan? sp=  db.KeyTimeToLive("name");

   

对于其他类型,可以序列化为string后写入。

  System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = serializer.Serialize(dict);

猜你喜欢

转载自www.cnblogs.com/81/p/9544087.html