redis 查看key的有效期_Redis中取得所有Key、过期时间配置与获取、Key过期通知。...

本文介绍了如何使用StackExchange.Redis库连接Redis并进行操作,包括设置Hash键值对,获取所有Keys,检查Key的过期时间和设置Key的过期时间。此外,还展示了订阅Redis频道以在Key过期时接收到通知的方法。
摘要由CSDN通过智能技术生成

string connection = "127.0.0.1:6379,password=xxxxx,connectRetry=5";

[TestMethod]public voidTestSet()

{var mutlti =StackExchange.Redis.ConnectionMultiplexer.Connect(connection);var db = mutlti.GetDatabase(0);

db.HashSetAsync("student1", newStackExchange.Redis.HashEntry[] {new StackExchange.Redis.HashEntry("name", "song"),new StackExchange.Redis.HashEntry("age", 11),new StackExchange.Redis.HashEntry("sex", "boy")

}).GetAwaiter().GetResult();

db.HashSetAsync("student2", newStackExchange.Redis.HashEntry[] {new StackExchange.Redis.HashEntry("name", "wang"),new StackExchange.Redis.HashEntry("age", 22),new StackExchange.Redis.HashEntry("sex", "girl")

}).GetAwaiter().GetResult();

mutlti.Close(true);

}

[TestMethod]public voidTestGetList()

{var mutlti =StackExchange.Redis.ConnectionMultiplexer.Connect(connection);var endpoints =mutlti.GetEndPoints();

List keyList = new List();foreach (var ep inendpoints)

{var server =mutlti.GetServer(ep);var keys = server.Keys(0, "*");foreach (var item inkeys)

{

keyList.Add((string)item);

}

}var db = mutlti.GetDatabase(0);

mutlti.Close(true);throw new Exception(string.Join(",", keyList));

}

[TestMethod]public voidTestGetTime()

{var mutlti =StackExchange.Redis.ConnectionMultiplexer.Connect(connection);var db = mutlti.GetDatabase(0);var server = mutlti.GetServer(mutlti.GetEndPoints()[0]);var timeNow =server.Time().ToUniversalTime();var time = db.KeyTimeToLive("student2");var expire = time == null ? (DateTime?)null : timeNow.Add(time.Value); //返回UTC时间。

throw new Exception(expire.Value.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss"));

}

[TestMethod]public voidTestSetTime()

{var mutlti =StackExchange.Redis.ConnectionMultiplexer.Connect(connection);var db = mutlti.GetDatabase(0);

db.KeyExpire("student2", DateTime.Now.AddHours(2));

}

[TestMethod]public voidTestNotifyOnExpire()

{//URL:https://docs.azure.cn/zh-cn/redis-cache/cache-configure

//填一个"__keyevent@*__:expired*"试试//如果不行的话,再改填成:"Kxg"这试试

var tsk = Task.Factory.StartNew(() =>{var mutlti =StackExchange.Redis.ConnectionMultiplexer.Connect(connection);var subscriber =mutlti.GetSubscriber();

subscriber.Subscribe("__keyspace@0__:*", (channel, notificationType) =>{

Debug.WriteLine(channel+ "|" +notificationType);

});while (true)

{

Thread.Sleep(1000);

}

});

tsk.Wait();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值